Browse Source

Add: pack, unpack

AnnulusGames 1 year ago
parent
commit
d5d6a1d971
2 changed files with 49 additions and 0 deletions
  1. 22 0
      src/Lua/Standard/Table/PackFunction.cs
  2. 27 0
      src/Lua/Standard/Table/UnpackFunction.cs

+ 22 - 0
src/Lua/Standard/Table/PackFunction.cs

@@ -0,0 +1,22 @@
+namespace Lua.Standard.Table;
+
+public sealed class PackFunction : LuaFunction
+{
+    public override string Name => "pack";
+    public static readonly PackFunction Instance = new();
+
+    protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
+    {
+        var table = new LuaTable(context.ArgumentCount, 1);
+
+        var span = context.Arguments;
+        for (int i = 0; i < span.Length; i++)
+        {
+            table[i + 1] = span[i];
+        }
+        table["n"] = span.Length;
+
+        buffer.Span[0] = table;
+        return new(1);
+    }
+}

+ 27 - 0
src/Lua/Standard/Table/UnpackFunction.cs

@@ -0,0 +1,27 @@
+namespace Lua.Standard.Table;
+
+public sealed class UnpackFunction : LuaFunction
+{
+    public override string Name => "unpack";
+    public static readonly UnpackFunction Instance = new();
+
+    protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
+    {
+        var arg0 = context.ReadArgument<LuaTable>(0);
+        var arg1 = context.ArgumentCount >= 2
+            ? (int)context.ReadArgument<double>(1)
+            : 1;
+        var arg2 = context.ArgumentCount >= 3
+            ? (int)context.ReadArgument<double>(2)
+            : arg0.ArrayLength;
+
+        var index = 0;
+        for (int i = arg1; i <= arg2; i++)
+        {
+            buffer.Span[index] = arg0[i];
+            index++;
+        }
+
+        return new(index);
+    }
+}