RemoveFunction.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. namespace Lua.Standard.Table;
  2. public sealed class RemoveFunction : LuaFunction
  3. {
  4. public override string Name => "remove";
  5. public static readonly RemoveFunction Instance = new();
  6. protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  7. {
  8. var table = context.GetArgument<LuaTable>(0);
  9. var n_arg = context.HasArgument(1)
  10. ? context.GetArgument<double>(1)
  11. : table.ArrayLength;
  12. LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, n_arg);
  13. var n = (int)n_arg;
  14. if (n <= 0 || n > table.GetArraySpan().Length)
  15. {
  16. if (!context.HasArgument(1) && n == 0)
  17. {
  18. buffer.Span[0] = LuaValue.Nil;
  19. return new(1);
  20. }
  21. throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'remove' (position out of bounds)");
  22. }
  23. else if (n > table.ArrayLength)
  24. {
  25. buffer.Span[0] = LuaValue.Nil;
  26. return new(1);
  27. }
  28. buffer.Span[0] = table.RemoveAt(n);
  29. return new(1);
  30. }
  31. }