lua-users home
lua-l archive

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


It's not used (i.e. never dereferenced) for anything by Lua or its
default allocator. It is a user data pointer, a very common thing in C
APIs in general. It allows you to pass data to your custom allocator.
In practice, you can store anything that fits into pointer type there,
not just pointers (integers are most reasonable, but tiny struct might
work too).

In theory, this could be a use case: you have your custom allocator
that can allocate memory in few different manners (say, in faster and
smaller vs slower and bigger regions) and you want to have your
different Lua states use different options. Then you can write

allocOpts* opts = malloc(sizeof(allocOpts));
opts.region = ALLOC_SLOW;
lua_newstate(my_alloc, opts);

Bottom line is that this option is only usable by custom allocators,
default one ignores it completely.

On Tue, 2020-10-20 at 15:58 +0800, 孙世龙 sunshilong wrote:
> Hi, list
> 
> What is the second argument of lua_newstate(lua_Alloc f, void *ud)
> used for?
> 
> As per the manual of
> Lua(https://www.lua.org/manual/5.3/manual.html#lua_Alloc), which says
> that:
> The second argument, ud, is an opaque pointer that Lua passes to the
> allocator in every call.
> 
> The second argument is NULL when lua_newsate() is called by
> luaL_newstate() which is invoked by main() function.
> For your reference, here is the related code snippet:
> LUALIB_API lua_State *luaL_newstate (void) {
>   lua_State *L = lua_newstate(l_alloc, NULL);
>   if (L) {
>     int *warnstate;  /* space for warning state */
>     lua_atpanic(L, &panic);
>     warnstate = (int *)lua_newuserdatauv(L, sizeof(int), 0);
>     luaL_ref(L, LUA_REGISTRYINDEX);  /* make sure it won't be
> collected */
>     *warnstate = 0;  /* default is warnings off */
>     lua_setwarnf(L, warnf, warnstate);
>   }
>   return L;
> }
> 
> 
> I am a little confused that when should I pass a valid pointer to
> lua_newstate() as a second argument?
> What is it used for?
> 
> I would be grateful to have some help with this question.
> It would better if you can give me some simple examples.
> 
> Best regards
> Sunshilong