InsertFunction.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. namespace Lua.Standard.Table;
  2. public sealed class InsertFunction : LuaFunction
  3. {
  4. public override string Name => "insert";
  5. public static readonly InsertFunction 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 value = context.HasArgument(2)
  10. ? context.GetArgument(2)
  11. : context.GetArgument(1);
  12. var pos = context.HasArgument(2)
  13. ? context.GetArgument<double>(1)
  14. : table.ArrayLength + 1;
  15. if (!MathEx.IsInteger(pos))
  16. {
  17. throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'insert' (number has no integer representation)");
  18. }
  19. if (pos <= 0 || pos > table.ArrayLength + 1)
  20. {
  21. throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'insert' (position out of bounds)");
  22. }
  23. table.Insert((int)pos, value);
  24. return new(0);
  25. }
  26. }