SetMetatableFunction.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using Lua.Runtime;
  2. namespace Lua.Standard.Basic;
  3. public sealed class SetMetatableFunction : LuaFunction
  4. {
  5. public override string Name => "setmetatable";
  6. public static readonly SetMetatableFunction Instance = new();
  7. protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  8. {
  9. var arg0 = context.ReadArgument<LuaTable>(0);
  10. var arg1 = context.ReadArgument(1);
  11. if (arg1.Type is not (LuaValueType.Nil or LuaValueType.Table))
  12. {
  13. LuaRuntimeException.BadArgument(context.State.GetTracebacks(), 2, Name, [LuaValueType.Nil, LuaValueType.Table]);
  14. }
  15. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Metatable, out _))
  16. {
  17. throw new LuaRuntimeException(context.State.GetTracebacks(), "cannot change a protected metatable");
  18. }
  19. else if (arg1.Type is LuaValueType.Nil)
  20. {
  21. arg0.Metatable = null;
  22. }
  23. else
  24. {
  25. arg0.Metatable = arg1.Read<LuaTable>();
  26. }
  27. buffer.Span[0] = arg0;
  28. return new(1);
  29. }
  30. }