Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - specifying library for coroutine

Within my Lua scripts, I have multiple libraries using the same 'structure'. For example, I have a.lua what contains require('b') and require('c'). Both b.lua and c.lua have got an info function. b.lua let it print "b" and c.lua let it print "c". In a.lua I want to start a coroutine with either the info() from B.lua or C.lua.

This is my b.lua:

b = {}
function b.info()
  coroutine.yield()
  print("b")
  print("b2")
end

C.lua has a similiar structure, but most B's are replaced with C. When trying to start the coroutine with local co = coroutine.create(b.info()) (what also is strange because usually it starts suspended) I get an error like "attempt to yield across metamethod/C-call boundary".

like image 512
scheurneus Avatar asked Sep 08 '26 07:09

scheurneus


1 Answers

coroutine.create(b.info()) calls b.info before resuming co.

You need to pass a function, not a function call, as in

local co = coroutine.create(b.info)
coroutine.resume(co)        -- prints nothing
coroutine.resume(co)        -- prints b, b2

or

co = coroutine.wrap(b.info)
co()
co()
like image 154
lhf Avatar answered Sep 12 '26 20:09

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!