LuaFunction.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using Lua.Runtime;
  2. namespace Lua;
  3. public abstract partial class LuaFunction
  4. {
  5. LuaThread? thread;
  6. public LuaThread? Thread => thread;
  7. internal void SetCurrentThread(LuaThread thread)
  8. {
  9. this.thread = thread;
  10. }
  11. public virtual string Name => GetType().Name;
  12. public async ValueTask<int> InvokeAsync(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  13. {
  14. var state = context.State;
  15. var frame = new CallStackFrame
  16. {
  17. Base = context.StackPosition == null ? state.Stack.Count - context.ArgumentCount : context.StackPosition.Value,
  18. CallPosition = context.SourcePosition,
  19. ChunkName = context.ChunkName ?? LuaState.DefaultChunkName,
  20. RootChunkName = context.RootChunkName ?? LuaState.DefaultChunkName,
  21. VariableArgumentCount = this is Closure closure ? context.ArgumentCount - closure.Proto.ParameterCount : 0,
  22. Function = this,
  23. };
  24. state.PushCallStackFrame(frame);
  25. try
  26. {
  27. return await InvokeAsyncCore(context, buffer, cancellationToken);
  28. }
  29. catch (Exception ex) when (ex is not (LuaException or OperationCanceledException))
  30. {
  31. throw new LuaRuntimeException(state.GetTracebacks(), ex.Message);
  32. }
  33. finally
  34. {
  35. state.PopCallStackFrame();
  36. }
  37. }
  38. protected abstract ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken);
  39. }