LuaFunction.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Runtime.CompilerServices;
  2. using Lua.Runtime;
  3. namespace Lua;
  4. public class LuaFunction(string name, Func<LuaFunctionExecutionContext, Memory<LuaValue>, CancellationToken, ValueTask<int>> func)
  5. {
  6. public string Name { get; } = name;
  7. internal Func<LuaFunctionExecutionContext, Memory<LuaValue>, CancellationToken, ValueTask<int>> Func { get; } = func;
  8. public LuaFunction(Func<LuaFunctionExecutionContext, Memory<LuaValue>, CancellationToken, ValueTask<int>> func) : this("anonymous", func)
  9. {
  10. }
  11. public async ValueTask<int> InvokeAsync(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  12. {
  13. var frame = new CallStackFrame
  14. {
  15. Base = context.FrameBase,
  16. VariableArgumentCount = this is LuaClosure closure ? Math.Max(context.ArgumentCount - closure.Proto.ParameterCount, 0) : 0,
  17. Function = this,
  18. };
  19. context.Thread.PushCallStackFrame(frame);
  20. try
  21. {
  22. if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook)
  23. {
  24. return await LuaVirtualMachine.ExecuteCallHook(context, buffer, cancellationToken);
  25. }
  26. return await Func(context, buffer, cancellationToken);
  27. }
  28. finally
  29. {
  30. context.Thread.PopCallStackFrame();
  31. }
  32. }
  33. }