Program.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Runtime.CompilerServices;
  2. using Lua.CodeAnalysis.Compilation;
  3. using Lua.Runtime;
  4. using Lua;
  5. using Lua.Standard;
  6. var state = LuaState.Create();
  7. state.OpenStandardLibraries();
  8. state.Environment["vec3"] = new LVec3();
  9. try
  10. {
  11. var source = File.ReadAllText(GetAbsolutePath("test.lua"));
  12. Console.WriteLine("Source Code " + new string('-', 50));
  13. Console.WriteLine(source);
  14. var closure = state.Compile(source, "test.lua");
  15. DebugChunk(closure.Proto, 0);
  16. Console.WriteLine("Output " + new string('-', 50));
  17. using var results = await state.RunAsync(closure);
  18. Console.WriteLine("Result " + new string('-', 50));
  19. for (int i = 0; i < results.Count; i++)
  20. {
  21. Console.WriteLine(results[i]);
  22. }
  23. Console.WriteLine("End " + new string('-', 50));
  24. }
  25. catch (Exception ex)
  26. {
  27. Console.WriteLine(ex);
  28. if (ex is LuaRuntimeException { InnerException: not null } luaEx)
  29. {
  30. Console.WriteLine(luaEx.InnerException);
  31. }
  32. }
  33. static string GetAbsolutePath(string relativePath, [CallerFilePath] string callerFilePath = "")
  34. {
  35. return Path.Combine(Path.GetDirectoryName(callerFilePath)!, relativePath);
  36. }
  37. static void DebugChunk(Prototype chunk, int id)
  38. {
  39. Console.WriteLine($"Chunk[{id}]" + new string('=', 50));
  40. Console.WriteLine($"Parameters:{chunk.ParameterCount}");
  41. Console.WriteLine("Code " + new string('-', 50));
  42. var index = 0;
  43. foreach (var inst in chunk.Code)
  44. {
  45. Console.WriteLine($"[{index}]\t{chunk.LineInfo[index]}\t\t{inst}");
  46. index++;
  47. }
  48. Console.WriteLine("LocalVariables " + new string('-', 50));
  49. index = 0;
  50. foreach (var local in chunk.LocalVariables)
  51. {
  52. Console.WriteLine($"[{index}]\t{local.Name}\t{local.StartPc}\t{local.EndPc}");
  53. index++;
  54. }
  55. Console.WriteLine("Constants " + new string('-', 50));
  56. index = 0;
  57. foreach (var constant in chunk.Constants.ToArray())
  58. {
  59. Console.WriteLine($"[{index}]\t{constant}");
  60. index++;
  61. }
  62. Console.WriteLine("UpValues " + new string('-', 50));
  63. index = 0;
  64. foreach (var upValue in chunk.UpValues.ToArray())
  65. {
  66. Console.WriteLine($"[{index}]\t{upValue.Name}\t{(upValue.IsLocal ? 1 : 0)}\t{upValue.Index}");
  67. index++;
  68. }
  69. Console.WriteLine();
  70. var nestedChunkId = 0;
  71. foreach (var localChunk in chunk.ChildPrototypes)
  72. {
  73. DebugChunk(localChunk, nestedChunkId);
  74. nestedChunkId++;
  75. }
  76. }