Friday 15 April 2011

coroutine - How to make a Lua function block until a closure is called -



coroutine - How to make a Lua function block until a closure is called -

i have custom lua interpreter executable basic socket functionality built in. it's not luasocket, , much using luasocket here, can't (so please don't suggest answer).

the socket api i'm working relies on asynchronous closures signal network operation complete. so, in code below, socketconnect() returns , onconnect() called later on when connection complete.

local function onconnect(cookie, err, sock) print("connected!") end local function connect(host, port) local success, err = socketconnect(host, port, onconnect) print("connecting...") end

so, here's question. want create connect() function block until onconnect() closure called. i'm pretty new @ lua, i'm hoping coroutines might helpful here?

edit: here's effort @ making function block using coroutine:

local connected = false local function onconnect(cookie, err, sock) print("connected!") connected = true end local coroconnect = coroutine.create( function() local success, err = socketconnect(m_shost, m_nport, onconnect); while not connected coroutine.yield() end end ) local function connect(shost, nport) m_shost = shost m_nport = nport while not coroutine.status(coroconnect) ~= "dead" coroutine.resume(coroconnect) print("connecting...") end end

if want utilize coroutines, along these lines may work (or give thought on try):

-- should socket property, plenty illustration local connected local function onconnect(cookie, err, sock) print("connected!") connected = true end local function connect(host, port) connected = false local success, err = socketconnect(host, port, onconnect) while not connected coroutine.yield() end print("connecting...") end

if create coroutine connect function , go on calling coroutine coroutine.resume until it's completed (coroutine.status coroutine homecoming 'dead'), desired result. obviously, can move while loop socketconnect function itself, create synchronous user perspective won't homecoming until onconnect executed.

lua coroutine

No comments:

Post a Comment