1
votes

I'm learning Lua and trying to create a simple coroutine. In Lua 5.1, the code below gives the error: "attempt to yield across metamethod/C-call boundary." I've read about that limitation and I can't see how it applies to my code. I tried it in Lua 5.2 and got "attempt to yield from outside a coroutine," which is equally confusing to me. I'm sure the answer will be embarrassingly obvious!

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()
1

1 Answers

2
votes

You are calling subLoop

    if co == nil then
      co = coroutine.create(subLoop())

instead of passing it to coroutine.create

    if co == nil then
      co = coroutine.create(subLoop)

This results in you attempting to yield from the main state / (not-really-)coroutine, which gives errors with varying descriptions across versions.