访问Lua变量

AccessingLuaVariables.cs

  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using LuaInterface;
  4. // 访问Lua变量
  5. public class AccessingLuaVariables : MonoBehaviour
  6. {
  7. private string script =
  8. @"
  9. print('Objs2Spawn is: '..Objs2Spawn)
  10. var2read = 42
  11. varTable = {1,2,3,4,5}
  12. varTable.default = 1
  13. varTable.map = {}
  14. varTable.map.name = 'map'
  15. meta = {name = 'meta'}
  16. setmetatable(varTable, meta)
  17. function TestFunc(strs)
  18. print('get func by variable')
  19. end
  20. ";
  21. void Start ()
  22. {
  23. LuaState lua = new LuaState();
  24. lua.Start();
  25. lua["Objs2Spawn"] = 5;
  26. lua.DoString(script);
  27. //通过LuaState访问
  28. Debugger.Log("Read var from lua: {0}", lua["var2read"]);
  29. Debugger.Log("Read table var from lua: {0}", lua["varTable.default"]);
  30. LuaFunction func = lua["TestFunc"] as LuaFunction;
  31. func.Call();
  32. func.Dispose();
  33. //cache成LuaTable进行访问
  34. LuaTable table = lua.GetTable("varTable");
  35. Debugger.Log("Read varTable from lua, default: {0} name: {1}", table["default"], table["map.name"]);
  36. table["map.name"] = "new";
  37. Debugger.Log("Modify varTable name: {0}", table["map.name"]);
  38. table.AddTable("newmap");
  39. LuaTable table1 = (LuaTable)table["newmap"];
  40. table1["name"] = "table1";
  41. Debugger.Log("varTable.newmap name: {0}", table1["name"]);
  42. table1.Dispose();
  43. table1 = table.GetMetaTable();
  44. if (table1 != null)
  45. {
  46. Debugger.Log("varTable metatable name: {0}", table1["name"]);
  47. }
  48. object[] list = table.ToArray();
  49. for (int i = 0; i < list.Length; i++)
  50. {
  51. Debugger.Log("varTable[{0}], is {1}", i, list[i]);
  52. }
  53. table.Dispose();
  54. lua.CheckTop();
  55. lua.Dispose();
  56. }
  57. }

?