lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Fri, Aug 5, 2016 at 5:28 PM, Leinen, Rick <> wrote:
>>>2016-08-05 22:15 GMT+02:00 Leinen, Rick <>:
>>>> Or I guess it is more correct to say the function returned.
>>>A function is a first-class value, so you can store it in any Lua table. For example, the registry.
>>Thanks Dirk,
>>Yes I have seen that done, but is there any way I can save it as a C type and use lua_pushvalue just before calling lua_pcall?.  This seems to be cleaner from >the C side.
>  >Rick Leinen
> Looking at this more closely, I don't think lua_pushvalue will work.  I got this from this answer on stack overflow:
> "Continue to use luaL_loadbuffer to load scripts. Load here means precompile. Just save the function left on the stack somewhere in your program (or leave it on the stack if you can). When the time comes to run a script, lua_pushvalue and lua_pcall it"
> I believe the responder was suggesting leaving it on the stack.  But he also suggested saving it in the C program which I like because I am going to have many scripts running.

The Lua API does not expose any "LuaObject" or similar type for direct
storage of arbitrary values such as functions. Only Lua types with a
direct counterpart in ANSI C (such as integers and floats) can be
stored directly in a C variable (and then only by calling the
appropriate API function to convert between the Lua type and the C
type). All other Lua values (such as Lua functions) can only be
accessed/used through the stack and can only be stored in a Lua table.

Thus, there is no way to store the function directly in a C variable.
The closest analog to that, if you want persistent global storage, is
to store it in the Lua registry (which is a table), and push it onto
the stack each time you need to call it. This is probably what the SO
poster meant by "save it somewhere in your program"; he/she just
wasn't clear enough about it. Either that, or he/she has the same
misconceptions you do/did.