ModuleLibrary.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using Lua.CodeAnalysis.Compilation;
  2. using Lua.Internal;
  3. using Lua.Runtime;
  4. namespace Lua.Standard;
  5. public sealed class ModuleLibrary
  6. {
  7. public static readonly ModuleLibrary Instance = new();
  8. public ModuleLibrary()
  9. {
  10. RequireFunction = new("require", Require);
  11. }
  12. public readonly LuaFunction RequireFunction;
  13. public async ValueTask<int> Require(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  14. {
  15. var arg0 = context.GetArgument<string>(0);
  16. var loaded = context.State.LoadedModules;
  17. if (!loaded.TryGetValue(arg0, out var loadedTable))
  18. {
  19. var module = await context.State.ModuleLoader.LoadAsync(arg0, cancellationToken);
  20. var chunk = LuaCompiler.Default.Compile(module.ReadText(), module.Name);
  21. using var methodBuffer = new PooledArray<LuaValue>(1);
  22. await new LuaClosure(context.State, chunk).InvokeAsync(context, methodBuffer.AsMemory(), cancellationToken);
  23. loadedTable = methodBuffer[0];
  24. loaded[arg0] = loadedTable;
  25. }
  26. buffer.Span[0] = loadedTable;
  27. return 1;
  28. }
  29. }