private string luaString = @" function cor() print('coroutine start') coroutine.wait(5) --等待几秒 print('5s ago') print('frameCount:' .. Time.frameCount) coroutine.step() --等待一帧 print('frameCount:' .. Time.frameCount) local www = UnityEngine.WWW('http://www.baidu.com') coroutine.www(www) --等待www响应 local s = tolua.tolstring(www.bytes) print(s:sub(1,128)) end local c = nil function testCor() c = coroutine.start(cor) --开始协成 end function stopCor() if c ~= nil then coroutine.stop(c) --停止协成 end end "; private LuaState lua; private LuaLooper looper; private LuaFunction func; // Use this for initialization void Awake () { lua = new LuaState (); lua.Start (); // 不执行绑定无法使用Wrap的函数,就是GameObject等Unity的内置类 LuaBinder.Bind (lua); // 添加了这个组件后,它会在c#每一帧驱动lua的协同完成所有的协同功能,这里的协同已经不单单是lua自身功能,而是tolua#模拟unity的所有的功能. looper = gameObject.AddComponent<LuaLooper> (); looper.luaState = lua; //指定虚拟机 lua.DoString(luaString); func = lua.GetFunction("testCor"); func.Call (); LuaFunction stopFunc = lua ["stopCor"] as LuaFunction; stopFunc.Call (); stopFunc.Dispose (); } void Destroy(){ //擦屁股操作 func.Dispose (); looper.Destroy (); lua.CheckTop (); lua.Dispose (); func = null; looper = null; lua = null; }