作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在通过这个 video tutorial 学习 lua ,它有这段代码:
co = coroutine.create(function()
for i=1,5 do
print(coroutine.yield(i))
end
end)
print(coroutine.resume(co,1,2))
print(coroutine.resume(co,3,4))
print(coroutine.resume(co,5,6))
print(coroutine.resume(co,7,8))
print(coroutine.resume(co,9,10))
print(coroutine.resume(co,11,12))
true 1
3 4
true 2
5 6
true 3
7 8
true 4
9 10
true 5
11 12
true
最佳答案
普通 Lua 函数有一个入口(传入参数)和一个导出(传出返回值):
local function f( a, b )
print( "arguments", a, b )
return "I'm", "done"
end
print( "f returned", f( 1, 2 ) )
--> arguments 1 2
--> f returned I'm done
return
的一部分列出。可以通过将函数调用表达式放在赋值语句的右侧或更大的表达式(例如另一个函数调用)内部来检索语句。
pcall()
调用一个函数并捕获可能在内部引发的任何运行时错误。参数通过将它们作为参数放入
pcall()
中来传递。函数调用(就在函数本身之后)。
pcall()
还附加一个额外的返回值,指示函数是正常退出还是通过错误退出。被调用函数的内部没有改变。
print( "f returned", pcall( f, 1, 2 ) )
--> arguments 1 2
--> f returned true I'm done
coroutine.resume()
调用协程的主函数而不是
pcall()
.参数的传递方式和额外的返回值保持不变:
local th = coroutine.create( f )
print( "f returns", coroutine.resume( th, 1, 2 ) )
--> arguments 1 2
--> f returns true I'm done
coroutine.yield()
.您可以通过
coroutine.yield()
传递值通过将它们作为参数放入
yield()
函数调用。这些值可以作为
coroutine.resume()
的返回值在外部检索。调用而不是正常的返回值。
coroutine.resume()
重新进入生成的协程。 .协程从中断处继续,额外的值传递给
coroutine.resume()
可用作
yield()
的返回值之前暂停协程的函数调用。
local function g( a, b )
print( "arguments", a, b )
local c, d = coroutine.yield( "a" )
print( "yield returned", c, d )
return "I'm", "done"
end
local th = coroutine.create( g )
print( "g yielded", coroutine.resume( th, 1, 2 ) )
print( "g returned", coroutine.resume( th, 3, 4 ) )
--> arguments 1 2
--> g yielded true a
--> yield returned 3 4
--> g returned true I'm done
coroutine.resume()
首先(重新)启动了协程。
1, 2
从第一个
resume()
没有出现在您的输出中:您的协程主函数没有列出任何参数,因此忽略了传递给它的所有参数(在第一个函数条目上)。同样,由于您的 main 函数不返回任何返回值,因此最后一个
resume()
除了
true
之外,不返回任何额外的返回值这也表明执行成功。
关于lua - 关于lua corountine的resume和yield函数的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069751/
我是一名优秀的程序员,十分优秀!