lua-users home
lua-l archive

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


On 2016-08-05 23:13, Leinen, Rick wrote:
> 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.

Functions (like most other "complex" types) are garbage collected.  In
order not to complicate the GC and introduce high risk of refcounting
bugs or other ugly things on the "user" side, you can't get such values
out of the Lua state.

Storage in the state is possible - in a table, by the reference
mechanism, etc. - but you can't get it out 'as is'.

What you can do (if you don't care about upvalues - these are not
stored), is to save the compiled function via lua_dump[1] and then load
it again later.  That will reduce the time needed to load it again (no
parsing of Lua code) and may be useful across several runs of the
program (or if you want to send the same function to several states).
It's generally not a good idea to do this during a single run.

If you're the only "user" in a Lua state and there's not much you do,
it's probably ok and really easy to store the function(s) as globals (by
lua_setglobal(L,name) [2] and lua_getglobal(L,name) [3], also see [4]).

If there's many functions you could create a table and store them in
there (create a table on load with lua_newtable [5], setglobal it with a
suitable name and then to store/get functions, getglobal the table and
get/setfield [6] the functions.)

The "fancy" version would be to hide that table in the registry (either
by a reasonably unique name or the reference mechanism), but that's
probably not necessary.

-- Marco

[1]: https://www.lua.org/manual/5.3/manual.html#lua_dump
[2]: https://www.lua.org/manual/5.3/manual.html#lua_setglobal
[3]: https://www.lua.org/manual/5.3/manual.html#lua_getglobal
[4]: https://www.lua.org/manual/5.3/manual.html#lua_call
[5]: https://www.lua.org/manual/5.3/manual.html#lua_newtable
[6]: https://www.lua.org/manual/5.3/manual.html#lua_getfield