使用协程出现错误

我不确定自己是否误解了协程的用法,以下是我的代码:

talk = coroutine.create(function ()
print("我将在60秒内发言")
end)

time = coroutine.create(function ()
if coroutine.status(talk) == running then
for i = 60, 0, -1 do
print(i)
end
sleep(1)
else
coroutine.resume(talk)
end

end)
coroutine.resume(time)

它只打印出我将在60秒内发言,并不会有倒计时。我该如何修复它?

点赞
用户6163994
用户6163994
talk = coroutine.create(function ()
print("我将在60秒内发言")
coroutine.resume(time)
end)

time = coroutine.create(function ()
for i = 60, 0, -1 do
print(i)
coroutine.resume(talk)
end

end)

coroutine.resume(time)
2016-04-25 01:54:47
用户6222712
用户6222712
talk = coroutine.create(function ()
    print("我会在60秒内说话")
    coroutine.yield()
end)

time = coroutine.create(function ()
    for i = 60, 0, -1 do
        coroutine.resume(talk)
        print(i)
    end
end)

coroutine.resume(time)
2016-04-25 02:05:39
用户1266551
用户1266551

你正在调用 sleep,但我没有在任何地方看到这个函数的声明。这里是一个实现了 sleep() 的修改版本:

local function sleep(time)
    local sleep_until = os.time() + time
    repeat until os.time() >= sleep_until
end

local time, talk

talk = coroutine.create(function ()
    print("我将在60秒内说话")
    coroutine.resume(time)
end)

time = coroutine.create(function ()
    while true do
        for i = 60, 0, -1 do
            print(i)
            sleep(1)
        end
        coroutine.resume(talk)
    end
end)

coroutine.resume(time)
2016-04-25 12:05:34