Lua协同

TestCoroutine.cs

  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using LuaInterface;
  5. //例子5和6展示的两套协同系统勿交叉使用,此为推荐方案
  6. public class TestCoroutine : MonoBehaviour
  7. {
  8. public TextAsset luaFile = null;
  9. private LuaState lua = null;
  10. private LuaLooper looper = null;
  11. void Awake ()
  12. {
  13. lua = new LuaState();
  14. lua.Start();
  15. LuaBinder.Bind(lua);
  16. looper = gameObject.AddComponent<LuaLooper>();
  17. looper.luaState = lua;
  18. lua.DoString(luaFile.text, "TestCoroutine.cs");
  19. LuaFunction f = lua.GetFunction("TestCortinue");
  20. f.Call();
  21. f.Dispose();
  22. f = null;
  23. }
  24. void OnDestroy()
  25. {
  26. looper.Destroy();
  27. lua.Dispose();
  28. lua = null;
  29. }
  30. void OnGUI()
  31. {
  32. if (GUI.Button(new Rect(50, 50, 120, 45), "Start Counter"))
  33. {
  34. LuaFunction func = lua.GetFunction("StartDelay");
  35. func.Call();
  36. func.Dispose();
  37. }
  38. else if (GUI.Button(new Rect(50, 150, 120, 45), "Stop Counter"))
  39. {
  40. LuaFunction func = lua.GetFunction("StopDelay");
  41. func.Call();
  42. func.Dispose();
  43. }
  44. else if (GUI.Button(new Rect(50, 250, 120, 45), "GC"))
  45. {
  46. lua.DoString("collectgarbage('collect')", "TestCoroutine.cs");
  47. Resources.UnloadUnusedAssets();
  48. }
  49. }
  50. }

TestLuaCoroutine.lua.bytes

  1. function fib(n)
  2. local a, b = 0, 1
  3. while n > 0 do
  4. a, b = b, a + b
  5. n = n - 1
  6. end
  7. return a
  8. end
  9. function CoFunc()
  10. print('Coroutine started')
  11. local i = 0
  12. for i = 0, 10, 1 do
  13. print(fib(i))
  14. coroutine.wait(0.1)
  15. end
  16. print("current frameCount: "..Time.frameCount)
  17. coroutine.step()
  18. print("yield frameCount: "..Time.frameCount)
  19. local www = UnityEngine.WWW("http://www.baidu.com")
  20. coroutine.www(www)
  21. local s = tolua.tolstring(www.bytes)
  22. print(s:sub(1, 128))
  23. print('Coroutine ended')
  24. end
  25. function TestCortinue()
  26. coroutine.start(CoFunc)
  27. end
  28. local coDelay = nil
  29. function Delay()
  30. local c = 1
  31. while true do
  32. coroutine.wait(1)
  33. print("Count: "..c)
  34. c = c + 1
  35. end
  36. end
  37. function StartDelay()
  38. coDelay = coroutine.start(Delay)
  39. end
  40. function StopDelay()
  41. coroutine.stop(coDelay)
  42. end

?