调用Lua方法

CallLuaFunction.cs

  1. //#define TEST_GC
  2. using UnityEngine;
  3. using System.Collections;
  4. using LuaInterface;
  5. using System;
  6. public class CallLuaFunction : MonoBehaviour
  7. {
  8. private string script =
  9. @" function luaFunc(num)
  10. return num + 1
  11. end
  12. test = {}
  13. test.luaFunc = luaFunc
  14. ";
  15. LuaFunction func = null;
  16. LuaState lua = null;
  17. string tips = null;
  18. void Start ()
  19. {
  20. #if !TEST_GC
  21. #if UNITY_5
  22. Application.logMessageReceived += ShowTips;
  23. #else
  24. Application.RegisterLogCallback(ShowTips);
  25. #endif
  26. #endif
  27. lua = new LuaState();
  28. lua.Start();
  29. lua.DoString(script);
  30. //Get the function object
  31. func = lua.GetFunction("test.luaFunc");
  32. if (func != null)
  33. {
  34. //有gc alloc
  35. object[] r = func.Call(123456);
  36. Debugger.Log("generic call return: {0}", r[0]);
  37. // no gc alloc
  38. int num = CallFunc();
  39. Debugger.Log("expansion call return: {0}", num);
  40. }
  41. lua.CheckTop();
  42. }
  43. void ShowTips(string msg, string stackTrace, LogType type)
  44. {
  45. tips += msg;
  46. tips += "\r\n";
  47. }
  48. #if !TEST_GC
  49. void OnGUI()
  50. {
  51. GUI.Label(new Rect(Screen.width / 2 - 200, Screen.height / 2 - 150, 400, 300), tips);
  52. }
  53. #endif
  54. void OnDestroy()
  55. {
  56. if (func != null)
  57. {
  58. func.Dispose();
  59. func = null;
  60. }
  61. lua.Dispose();
  62. lua = null;
  63. #if !TEST_GC
  64. #if UNITY_5
  65. Application.logMessageReceived -= ShowTips;
  66. #else
  67. Application.RegisterLogCallback(null);
  68. #endif
  69. #endif
  70. }
  71. int CallFunc()
  72. {
  73. func.BeginPCall();
  74. func.Push(123456);
  75. func.PCall();
  76. int num = (int)func.CheckNumber();
  77. func.EndPCall();
  78. return num;
  79. }
  80. //在profiler中查看gc alloc
  81. #if TEST_GC
  82. void Update ()
  83. {
  84. func.Call(123456);
  85. //CallFunc();
  86. }
  87. #endif
  88. }

?