Lua: lua_resume和lua_yield参数的目的

lua_resume 和 lua_yield 中传递参数的目的是什么?

我理解,在第一次调用 lua_resume 时,参数被传递到正在被恢复的 Lua 函数中。这是有道理的。但我希望所有后续调用 lua_resume 都会 "更新" 协程函数中的参数。但实际并非如此。

那么,传递参数给 lua_resume 以便于 lua_yield 返回的目的是什么?正在协程中运行的 Lua 函数能否访问由 lua_resume 传递的参数?

点赞
用户734069
用户734069

Lua 不能以神奇的方式为原始参数提供新值。这可能取决于优化情况,它们可能甚至不再位于堆栈中。此外,没有指示代码何时中断,因此它可能无法再次看到这些参数。例如,如果协同程序调用了一个函数,则新函数无法看到传递到旧函数中的参数。

coroutine.yield() 返回传递给 resume 调用的参数,以便中断调用可以根据自己的需求进行处理。它允许进行恢复的代码与进行中断的特定代码通信。yield() 将其参数作为从 resume 返回的返回值传递,而 resume 则将其参数作为从 yield 返回的返回值传递。这建立了一条通信路径。

你不能用其他方式做到这一点。特别是不能修改可能无法从中断站点看到的参数。这很简单,优雅,并且很有意义。

另外,去篡改某人的值被认为是极为无礼的。尤其是在已经运行的函数上。记住:参数只是填有值的局部变量。除非它自己修改了它们,否则用户不应该期望这些变量的内容会改变。毕竟,它们是“局部”变量。它们只能在本地更改;因此得名。

2012-11-16 21:19:20
用户1442917
用户1442917

如Nicol所说。如果需要,您仍然可以保留第一次resume调用中的值:

do
  local firstcall
  function willyield(a)
    firstcall = a
    while a do
      print(a, firstcall)
      a = coroutine.yield()
    end
  end
end

local coro = coroutine.create(willyield)
coroutine.resume(coro, 1) // 1
coroutine.resume(coro, 10) // 10
coroutine.resume(coro, 100) // 100
coroutine.resume(coro) // 1

会输出

1 1
10 1
100 1
2012-11-16 21:28:00
用户5506400
用户5506400

一个简单的例子:

co = coroutine.create (function (a, b)
       print("First  args: ", a, b)
       coroutine.yield(a+10, b+10)
       print("Second args: ", a, b)
       coroutine.yield(a+10, b+10)
     end)
print(coroutine.resume(co, 1, 2))
print(coroutine.resume(co, 3, 4))

输出:

First  args:    1       2
true    11      12
Second args:    1       2
true    11      12

这表明参数 ab 的初始值没有改变。

2020-05-06 12:16:30