lua-users home
lua-l archive

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


>>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

>Marco-
>
>My desire is to use the same chunk with multiple states, so it sounds like your suggestion of using lua_dump makes sense.  I do have a few questions (I'm >still a novice on the API side of Lua):
>
>1) How do upvalues play a part with lua_dump?
>2) I see that lua_dump requires a Lua writer.  Is this something I have to create myself?
>3) How do I call the state with the dumped chunk?
>4) Is there an example of this you can point me to?
>
>Thanks,
>
>Rick

It might be helpful to add that I am currently developing on an embedded system with no operating system.  This will eventually run on a PC run Windows and/or Linux.