Browse Source

Improve: table.insert/remove

AnnulusGames 1 year ago
parent
commit
7eb4ab4fad
2 changed files with 13 additions and 15 deletions
  1. 5 6
      src/Lua/Standard/Table/InsertFunction.cs
  2. 8 9
      src/Lua/Standard/Table/RemoveFunction.cs

+ 5 - 6
src/Lua/Standard/Table/InsertFunction.cs

@@ -13,21 +13,20 @@ public sealed class InsertFunction : LuaFunction
             ? context.GetArgument(2)
             : context.GetArgument(1);
 
-        var pos = context.HasArgument(2)
+        var pos_arg = context.HasArgument(2)
             ? context.GetArgument<double>(1)
             : table.ArrayLength + 1;
 
-        if (!MathEx.IsInteger(pos))
-        {
-            throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'insert' (number has no integer representation)");
-        }
+        LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, pos_arg);
+
+        var pos = (int)pos_arg;
 
         if (pos <= 0 || pos > table.ArrayLength + 1)
         {
             throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'insert' (position out of bounds)");
         }
 
-        table.Insert((int)pos, value);
+        table.Insert(pos, value);
         return new(0);
     }
 }

+ 8 - 9
src/Lua/Standard/Table/RemoveFunction.cs

@@ -7,22 +7,21 @@ public sealed class RemoveFunction : LuaFunction
 
     protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
     {
-        var arg0 = context.GetArgument<LuaTable>(0);
-        var arg1 = context.HasArgument(1)
+        var table = context.GetArgument<LuaTable>(0);
+        var n_arg = context.HasArgument(1)
             ? context.GetArgument<double>(1)
-            : arg0.ArrayLength;
+            : table.ArrayLength;
 
-        if (!MathEx.IsInteger(arg1))
-        {
-            throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'remove' (number has no integer representation)");
-        }
+        LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, n_arg);
+
+        var n = (int)n_arg;
 
-        if (arg1 <= 0 || arg1 > arg0.ArrayLength)
+        if (n <= 0 || n > table.ArrayLength)
         {
             throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'remove' (position out of bounds)");
         }
 
-        buffer.Span[0] = arg0.RemoveAt((int)arg1);
+        buffer.Span[0] = table.RemoveAt(n);
         return new(1);
     }
 }