Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: lua_resume and lua_yield argument purposes

What is the purpose of passing arguments to lua_resume and lua_yield?

I understand that on the first call to lua_resume the arguments are passed to the lua function that is being resumed. This makes sense. However I'd expect that all subsequent calls to lua_resume would "update" the arguments in the coroutine's function. However that's not the case.

What is the purpose of passing arguments to lua_resume for lua_yield to return? Can the lua function running under the coroutine have access to the arguments passed by lua_resume?

like image 855
RandyGaul Avatar asked Nov 16 '12 21:11

RandyGaul


People also ask

What are Lua States?

A Lua state is a C pointer to an opaque data structure. This structure knows everything about a running Lua environment, including all global values, closures, coroutines, and loaded modules. Virtually every function in Lua's C API accepts a Lua state as its first parameter.

What is yield Lua?

The real power of coroutines stems from the yield function, which allows a running coroutine to suspend its execution so that it can be resumed later.

What are coroutines Lua?

Coroutines are blocks of Lua code which are created within Lua, and have their own flow of control like threads. Only one coroutine ever runs at a time, and it runs until it activates another coroutine, or yields (returns to the coroutine that invoked it).


1 Answers

What Nicol said. You can still preserve the values from the first resume call if you want:

do
  local firstcall
  function willyield(a)
    firstcall = a
    while a do
      print(a, firstcall)
      a = coroutine.yield()
    end
  end
end

local coro = coroutine.create(willyield)
coroutine.resume(coro, 1)
coroutine.resume(coro, 10)
coroutine.resume(coro, 100)
coroutine.resume(coro)

will print

1 1
10 1
100 1
like image 178
Paul Kulchenko Avatar answered Sep 29 '22 13:09

Paul Kulchenko