如何正确重新执行协程?

我正在使用 Lua 制作一款游戏,在游戏间隙和游戏回合中都需要运行定时器。游戏最初会有15秒的休息时间。在这种情况下,定时器可以正常运行,但是再次调用该函数时,似乎根本不触发……有什么提示吗?

我尝试将协程创建方法从 coroutine.create() 更改为 coroutine.wrap()。然而,在第一次调用成功运行后,协程的状态仍然显示为 yielding。

简化后的逻辑如下:其中,seconds 是整数,ending 是布尔值。

module.startTimer = coroutine.create(function(seconds, ending)
    wait()
    print("计时器开始运行,持续时间:" .. seconds .. " 秒,回合结束:" .. tostring(ending))
    while seconds > -1 do
        wait(1)
        seconds = seconds - 1
    end
    if ending == true then
        coroutine.yield(module.startTimer)
    else
        coroutine.yield(module.startTimer)
    end
end)

第一次调用(正常):

print(coroutine.status(module.startTimer))
coroutine.resume(module.startTimer, 15, false)
wait(1)
print(coroutine.status(module.startTimer))

输出:suspended, suspended

第二次调用(不正常):其中,RoundLength.Value 是一个可验证的整数值(300),已经成功打印出来了。

print(coroutine.status(module.startTimer))
coroutine.resume(module.startTimer, CURRENT_ROUND:FindFirstChild("RoundLength").Value, true)
wait()
print(coroutine.status(module.startTimer))
wait(CURRENT_ROUND:FindFirstChild("RoundLength").Value)

没有输出,没有执行,startTimer 没有打印状态。

点赞
用户1676313
用户1676313

我认为您可能误解了Lua的协程(它们与普通协程不同,因为它们是不对称的),但我不能确定。

如写所述,该函数将循环直到时间用尽,然后将自己yield(?)使得其自己的函数值从coroutine.resume调用中返回。

一旦它被恢复,它就从couroutine.yield调用再次开始,在函数结尾处返回并结束协程的执行。

2019-04-30 02:07:33