lua-users home
lua-l archive

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


> One seemingly stupid question to which I've been unable to find
> definitive answer in the docs.
> 
> In lua_tostring() docs last paragrah reads "Because Lua has garbage
> collection, there is no guarantee that the pointer returned by
> lua_tolstring will be valid after the corresponding Lua value is
> removed from the stack. ".
> 
> Must it be kept in the stack or is it enoguh if I keep the original
> value referenced. I.e., I'm inside a method of one of my classes ( so
> I have a this pointer ) and I've arrived there from a C function which
> has the relevant userdata as first argument, index 1, and I have a
> string at the TOS, if I do:
> 
> const char * s = lua_tostring(L,-1,0);
> 
> and then take it off the stack but keep it by doing
> 
> lua_setuservalue(L, 1);
> 
> or alternatively:
> 
> lua_rawsetp(L, LUA_REGISTRYINDEX, this);
> 
> Can I still keep using s safely?
> 
> And also,  can I keep using s if I guarantee nobody has messed with
> the uservalue/registry?
> 
> It seems likely, and it is true on userdata, but the wording on
> lua_tostring make me fear the string can me moved around by the
> collector if it is not pinned especifically by a stack entry.

I think the docs are quite clear; your fear is intentional.

Currently the collector does not move strings around, but this
is an implementation detail that can change in the future and
then create really hard-to-find bugs in your code.

- Concrete example: recently it was discussed in this list the
idea of using an unboxed representation for small strings. If we
decide to adopt that proposal, we will ensure that elements active
in the stack do not move (because the manual assures that), but
elements in a table (e.g., the registry) are free to be moved if
the table resizes.

-- Roberto