普通 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
注意,yield 不需要直接在协程的主函数中,它可以在嵌套函数调用中。执行会跳回到最初(重新)启动协程的coroutine.resume()。
现在回答您的问题,为什么第一个 resume() 中的 1, 2 没有出现在您的输出中:您的协程主函数没有列出任何参数,因此忽略了传递给它的所有参数(在第一个函数上入口)。同样,由于您的 main 函数不返回任何返回值,因此最后一个 resume() 不返回任何额外的返回值,除了表示成功执行的 true。