lua-users home
lua-l archive

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


On Sat, Nov 7, 2020 at 1:30 PM Ranier Vilela <ranier.vf@gmail.com> wrote:
[...]
return 1; /* Must return value (MyValue) */

Howto return to Lua MyValue struct (userdata)?
MyItem needs to be allocated by malloc rather than lua_newuserdata?

Without testing, it should be (almost) as simple as making sure that at the line above, the MyValue userdata is on the top of the Lua stack. There are API functions to move things around on the stack. Then "return 1;" will return the top item on the stack, which is MyValue.

MyItem can be a userdata (and in fact that's probably preferable to malloc because you gain automatic memory management and don't have to remember to call free() later), but the catch you must keep it (the userdata object, not just the struct) reachable by Lua or else it will be quickly garbage collected. Since MyItem is directly connected to MyValue, the best way to do this is most likely to add a user value to MyValue (using the API functions for that), with that user value being MyItem. Then MyItem will not be garbage collected as long as MyValue is alive.