举例详解Lua中的协同程序编程

这篇文章主要介绍了Lua中的协同程序编程,是Lua入门学习中的基础知识,需要的朋友可以参考下

 协同程序是协同的性质,可以把两个或更多的方法以可控制的方式执行。随着协同程序,在任何给定的时间,只有其协同程序运行之一,这在运行协同程序只能暂停其执行时,明确要求暂停。

上述定义可能看起来模糊。来告诉它更清楚,假设我们有两个方法,一个主程序方法和协同程序。当我们使用恢复功能调用协程,其开始执行,当我们调用yield功能,暂停执行。再次同协程可以继续从它被暂停的另一个恢复功能调用执行。这个过程可以继续,直到执行了协程的结束。
协同程序可用的功能

下表列出了在Lua协同程序及其相应的使用所有的可用功能。

2015529101326508.jpg-600 (648×454)

 例子

让我们看一个例子就明白了协程的概念。

复制代码 代码如下:
co = coroutine.create(function (value1,value2)
   local tempvar3 =10
   print("coroutine section 1", value1, value2, tempvar3)
   local tempvar1 = coroutine.yield(value1+1,value2+1)
   tempvar3 = tempvar3 + value1
   print("coroutine section 2",tempvar1 ,tempvar2, tempvar3)
   local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2)
   tempvar3 = tempvar3 + value1
   print("coroutine section 3",tempvar1,tempvar2, tempvar3)
   return value2, "end"
end)

print("main", coroutine.resume(co, 3, 2))
print("main", coroutine.resume(co, 12,14))
print("main", coroutine.resume(co, 5, 6))
print("main", coroutine.resume(co, 10, 20))

以上就是举例详解Lua中的协同程序编程的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Lua