Lua 中简单协程的复杂问题
Perplexing issue with simple coroutine in Lua
我正在学习 Lua 并尝试创建一个简单的协程。在 Lua 5.1 中,下面的代码给出了错误: "attempt to yield across metamethod/C-call boundary." 我已经阅读了有关该限制的信息,但我看不出它如何适用于我的代码。我在 Lua 5.2 中尝试过它并得到 "attempt to yield from outside a coroutine," 这同样让我感到困惑。我相信答案会非常明显!
output = {}
done = false
function mainLoop()
while not done do
if co == nil then
co = coroutine.create(subLoop())
elseif coroutine.status(co) == "suspended" then
print(output[k])
coroutine.resume(co)
elseif coroutine.status(co) == "dead" then
done = true
end
end
end
function subLoop()
for k=1, 20 do
table.insert(output, "This is line " .. k .. " of the test output")
coroutine.yield()
end
end
mainLoop()
您正在呼叫subLoop
if co == nil then
co = coroutine.create(subLoop())
而不是传递给 coroutine.create
if co == nil then
co = coroutine.create(subLoop)
这会导致您尝试 yield
从主状态/(不是真正的)协同程序,这会在不同版本中产生不同描述的错误。
我正在学习 Lua 并尝试创建一个简单的协程。在 Lua 5.1 中,下面的代码给出了错误: "attempt to yield across metamethod/C-call boundary." 我已经阅读了有关该限制的信息,但我看不出它如何适用于我的代码。我在 Lua 5.2 中尝试过它并得到 "attempt to yield from outside a coroutine," 这同样让我感到困惑。我相信答案会非常明显!
output = {}
done = false
function mainLoop()
while not done do
if co == nil then
co = coroutine.create(subLoop())
elseif coroutine.status(co) == "suspended" then
print(output[k])
coroutine.resume(co)
elseif coroutine.status(co) == "dead" then
done = true
end
end
end
function subLoop()
for k=1, 20 do
table.insert(output, "This is line " .. k .. " of the test output")
coroutine.yield()
end
end
mainLoop()
您正在呼叫subLoop
if co == nil then
co = coroutine.create(subLoop())
而不是传递给 coroutine.create
if co == nil then
co = coroutine.create(subLoop)
这会导致您尝试 yield
从主状态/(不是真正的)协同程序,这会在不同版本中产生不同描述的错误。