Browse Source

Add: coroutine.wrap

AnnulusGames 1 year ago
parent
commit
b94837b68a

+ 0 - 1
src/Lua/Standard/Coroutines/CoroutineResumeFunction.cs

@@ -10,7 +10,6 @@ public sealed class CoroutineResumeFunction : LuaFunction
     protected override async ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
     protected override async ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
     {
     {
         var thread = context.ReadArgument<LuaThread>(0);
         var thread = context.ReadArgument<LuaThread>(0);
-
         return await thread.Resume(context, buffer, cancellationToken);
         return await thread.Resume(context, buffer, cancellationToken);
     }
     }
 }
 }

+ 25 - 0
src/Lua/Standard/Coroutines/CoroutineWrapFunction.cs

@@ -0,0 +1,25 @@
+
+namespace Lua.Standard.Coroutines;
+
+public sealed class CoroutineWrapFunction : LuaFunction
+{
+    public const string FunctionName = "wrap";
+
+    public override string Name => FunctionName;
+
+    protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
+    {
+        var arg0 = context.ReadArgument<LuaFunction>(0);
+        var thread = new LuaThread(context.State, arg0, false);
+        buffer.Span[0] = new Wrapper(thread);
+        return new(1);
+    }
+
+    class Wrapper(LuaThread targetThread) : LuaFunction
+    {
+        protected override async ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
+        {
+            return await targetThread.Resume(context, buffer, cancellationToken);
+        }
+    }
+}

+ 1 - 0
src/Lua/Standard/OpenLibExtensions.cs

@@ -80,6 +80,7 @@ public static class OpenLibExtensions
         table[CoroutineYieldFunction.FunctionName] = new CoroutineYieldFunction();
         table[CoroutineYieldFunction.FunctionName] = new CoroutineYieldFunction();
         table[CoroutineStatusFunction.FunctionName] = new CoroutineStatusFunction();
         table[CoroutineStatusFunction.FunctionName] = new CoroutineStatusFunction();
         table[CoroutineRunningFunction.FunctionName] = new CoroutineRunningFunction();
         table[CoroutineRunningFunction.FunctionName] = new CoroutineRunningFunction();
+        table[CoroutineWrapFunction.FunctionName] = new CoroutineWrapFunction();
 
 
         state.Environment["coroutine"] = table;
         state.Environment["coroutine"] = table;
     }
     }