gpt4 book ai didi

lua - 关于lua corountine的resume和yield函数的困惑

转载 作者:行者123 更新时间:2023-12-04 13:50:37 25 4
gpt4 key购买 nike

我正在通过这个 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

但是我不明白yield和resume如何相互传递参数以及为什么yield不输出resume传递给它的第一个1,2,有人可以解释一下吗?谢谢

最佳答案

普通 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

参数通过将它们放在括号内来绑定(bind)到参数名称(局部变量),返回值作为 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

请注意,yield 不必直接在协程的主函数中,它可以在嵌套函数调用中。执行跳回到 coroutine.resume()首先(重新)启动了协程。

现在回答你的问题,为什么 1, 2从第一个 resume()没有出现在您的输出中:您的协程主函数没有列出任何参数,因此忽略了传递给它的所有参数(在第一个函数条目上)。同样,由于您的 main 函数不返回任何返回值,因此最后一个 resume()除了 true 之外,不返回任何额外的返回值这也表明执行成功。

关于lua - 关于lua corountine的resume和yield函数的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com