Lua线程

TestLuaThread.cs

  1. using UnityEngine;
  2. using System.Collections;
  3. using LuaInterface;
  4. public class TestLuaThread : MonoBehaviour
  5. {
  6. string script =
  7. @"
  8. function fib(n)
  9. local a, b = 0, 1
  10. while n > 0 do
  11. a, b = b, a + b
  12. n = n - 1
  13. end
  14. return a
  15. end
  16. function CoFunc(len)
  17. print('Coroutine started')
  18. local i = 0
  19. for i = 0, len, 1 do
  20. local flag = coroutine.yield(fib(i))
  21. if not flag then
  22. break
  23. end
  24. end
  25. print('Coroutine ended')
  26. end
  27. function Test()
  28. local co = coroutine.create(CoFunc)
  29. return co
  30. end
  31. ";
  32. LuaState state = null;
  33. LuaThread thread = null;
  34. void Start ()
  35. {
  36. state = new LuaState();
  37. state.Start();
  38. state.LogGC = true;
  39. state.DoString(script);
  40. LuaFunction func = state.GetFunction("Test");
  41. func.BeginPCall();
  42. func.PCall();
  43. thread = func.CheckLuaThread();
  44. thread.name = "LuaThread";
  45. func.EndPCall();
  46. func.Dispose();
  47. func = null;
  48. thread.Resume(10);
  49. }
  50. void OnDestroy()
  51. {
  52. if (thread != null)
  53. {
  54. thread.Dispose();
  55. thread = null;
  56. }
  57. state.Dispose();
  58. state = null;
  59. }
  60. void Update()
  61. {
  62. state.CheckTop();
  63. state.Collect();
  64. }
  65. void OnGUI()
  66. {
  67. if (GUI.Button(new Rect(10, 10, 120, 40), "Resume Thead"))
  68. {
  69. if (thread != null && thread.Resume(true) == (int)LuaThreadStatus.LUA_YIELD)
  70. {
  71. object[] objs = thread.GetResult();
  72. Debugger.Log("lua yield: " + objs[0]);
  73. }
  74. }
  75. else if (GUI.Button(new Rect(10, 60, 120, 40), "Close Thread"))
  76. {
  77. if (thread != null)
  78. {
  79. thread.Dispose();
  80. thread = null;
  81. }
  82. }
  83. }
  84. }

?