LoadFunction.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using Lua.CodeAnalysis.Compilation;
  2. using Lua.Runtime;
  3. namespace Lua.Standard.Basic;
  4. public sealed class LoadFunction : LuaFunction
  5. {
  6. public override string Name => "load";
  7. public static readonly LoadFunction Instance = new();
  8. protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  9. {
  10. // Lua-CSharp does not support binary chunks, the mode argument is ignored.
  11. var arg0 = context.GetArgument(0);
  12. var arg1 = context.HasArgument(1)
  13. ? context.GetArgument<string>(1)
  14. : null;
  15. var arg3 = context.HasArgument(3)
  16. ? context.GetArgument<LuaTable>(3)
  17. : null;
  18. // do not use LuaState.DoFileAsync as it uses the new LuaFunctionExecutionContext
  19. try
  20. {
  21. if (arg0.TryRead<string>(out var str))
  22. {
  23. var chunk = LuaCompiler.Default.Compile(str, arg1 ?? "chunk");
  24. buffer.Span[0] = new Closure(context.State, chunk, arg3);
  25. return new(1);
  26. }
  27. else if (arg0.TryRead<LuaFunction>(out var function))
  28. {
  29. // TODO:
  30. throw new NotImplementedException();
  31. }
  32. else
  33. {
  34. LuaRuntimeException.BadArgument(context.State.GetTraceback(), 1, Name);
  35. return default; // dummy
  36. }
  37. }
  38. catch (Exception ex)
  39. {
  40. buffer.Span[0] = LuaValue.Nil;
  41. buffer.Span[1] = ex.Message;
  42. return new(2);
  43. }
  44. }
  45. }