ToLua协同程序(coroutine)

ToLua协同程序

之前文章转载过一篇Lua的协同程序,在Tolua中其实内部重写了部分lua的协同程序的方法,所以原理基本类似,只是用法改变了。

基本语法

方法 描述
coroutine.start(协程函数,num1,num2,…) 协程函数的开启
coroutine.step(count) 协程函数的挂起
coroutine.wait(延时时间) 协程函数的延时 注意:时间的单位是秒
coroutine.stop(协程对象) 协程函数的结束 注意:协程函数关闭的协程对象是对应的协程开启函数的返回值
coroutine.www(网址) 协程下载
WaitForSeconds(延时时间) 等待延迟时间
WaitForFixedUpdate() 等待fixedupdate渲染结束
WaitForEndOfFrame() 等待OnGUI渲染结束
Yield(null) 等待CPU执行一帧
Yield(0) 等待CPU执行一帧
Yield(www) 等待www结束

这里第一次用到luastate.Start()函数,因为这次需要wrap提供功能,因此必须启动它,里面比较关键是gameObject.AddComponent《LuaLooper》();添加了这个组件后,它会在c#每一帧驱动lua的协同完成所有的协同功能,这里的协同已经不单单是lua自身功能,而是tolua#模拟unity的所有的功能。

例子如下:

function fib(n)
    local a, b = 0, 1
    while n > 0 do
        a, b = b, a + b
        n = n - 1
    end

    return a
end

function CoFunc()
    print('Coroutine started')    
    for i = 0, 10, 1 do
        print(fib(i))                    
        coroutine.wait(0.1)						
    end	
	print("current frameCount: "..Time.frameCount)
	coroutine.step()
	print("yield frameCount: "..Time.frameCount)

	local www = UnityEngine.WWW("http://www.baidu.com")
	coroutine.www(www)
	local s = tolua.tolstring(www.bytes)
	print(s:sub(1, 128))
    print('Coroutine ended')
end

function TestCortinue()	
    coroutine.start(CoFunc)
end

结果:
在这里插入图片描述

发布了62 篇原创文章 · 获赞 5 · 访问量 3947

猜你喜欢

转载自blog.csdn.net/qq_42194657/article/details/102761022