using System.Runtime.CompilerServices; using Lua.Runtime; namespace Lua; public class LuaFunction(string name, Func, CancellationToken, ValueTask> func) { public string Name { get; } = name; internal Func, CancellationToken, ValueTask> Func { get; } = func; public LuaFunction(Func, CancellationToken, ValueTask> func) : this("anonymous", func) { } public async ValueTask InvokeAsync(LuaFunctionExecutionContext context, Memory buffer, CancellationToken cancellationToken) { var frame = new CallStackFrame { Base = context.FrameBase, VariableArgumentCount = this is LuaClosure closure ? Math.Max(context.ArgumentCount - closure.Proto.ParameterCount, 0) : 0, Function = this, }; context.Thread.PushCallStackFrame(frame); try { if (context.Thread.CallOrReturnHookMask.Value != 0 && !context.Thread.IsInHook) { return await LuaVirtualMachine.ExecuteCallHook(context, buffer, cancellationToken); } return await Func(context, buffer, cancellationToken); } finally { context.Thread.PopCallStackFrame(); } } }