Program.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using Lua.CodeAnalysis.Syntax;
  2. using Lua.CodeAnalysis.Compilation;
  3. using Lua.Runtime;
  4. using Lua;
  5. using Lua.Standard;
  6. var state = LuaState.Create();
  7. state.OpenBaseLibrary();
  8. try
  9. {
  10. var source =
  11. @"
  12. metatable = {
  13. __add = function(a, b)
  14. local t = { }
  15. for i = 1, #a do
  16. t[i] = a[i] + b[i]
  17. end
  18. return t
  19. end
  20. }
  21. local a = { 1, 2, 3 }
  22. local b = { 4, 5, 6 }
  23. setmetatable(a, metatable)
  24. return a + b
  25. ";
  26. var syntaxTree = LuaSyntaxTree.Parse(source, "main.lua");
  27. Console.WriteLine("Source Code " + new string('-', 50));
  28. var debugger = new DisplayStringSyntaxVisitor();
  29. Console.WriteLine(debugger.GetDisplayString(syntaxTree));
  30. var chunk = LuaCompiler.Default.Compile(syntaxTree, "main.lua");
  31. var id = 0;
  32. DebugChunk(chunk, ref id);
  33. Console.WriteLine("Output " + new string('-', 50));
  34. var results = new LuaValue[64];
  35. var resultCount = await state.RunAsync(chunk, results);
  36. Console.WriteLine("Result " + new string('-', 50));
  37. for (int i = 0; i < resultCount; i++)
  38. {
  39. Console.WriteLine(results[i]);
  40. }
  41. Console.WriteLine("End " + new string('-', 50));
  42. }
  43. catch (Exception ex)
  44. {
  45. Console.WriteLine(ex);
  46. }
  47. static void DebugChunk(Chunk chunk, ref int id)
  48. {
  49. Console.WriteLine($"Chunk[{id++}]" + new string('=', 50));
  50. Console.WriteLine("Instructions " + new string('-', 50));
  51. var index = 0;
  52. foreach (var inst in chunk.Instructions.ToArray())
  53. {
  54. Console.WriteLine($"[{index}]\t{chunk.SourcePositions[index]}\t{inst}");
  55. index++;
  56. }
  57. Console.WriteLine("Constants " + new string('-', 50)); index = 0;
  58. foreach (var constant in chunk.Constants.ToArray())
  59. {
  60. Console.WriteLine($"[{index}]\t{constant}");
  61. index++;
  62. }
  63. Console.WriteLine("UpValues " + new string('-', 50)); index = 0;
  64. foreach (var upValue in chunk.UpValues.ToArray())
  65. {
  66. Console.WriteLine($"[{index}]\t{upValue.Name}\t{(upValue.IsInRegister ? 1 : 0)}\t{upValue.Index}");
  67. index++;
  68. }
  69. Console.WriteLine();
  70. foreach (var localChunk in chunk.Functions)
  71. {
  72. DebugChunk(localChunk, ref id);
  73. }
  74. }