[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Avoiding string duplication
- From: Sean Conner <sean@...>
- Date: Tue, 5 Nov 2019 11:52:42 -0500
It was thus said that the Great Chris Smith once stated:
> Hi all,
> I’m trying to understand a bit better the handling of strings in Lua with
> respect to memory allocation and what is safe or unsafe when using the C
> API. The context for this is that I’m dealing with some (constant)
> strings that are used by both C and Lua code, and I’d like to avoid
> unnecessary memory allocations.
Lua keeps a copy of every string used. When a string is referenced, for
and it does not exist in the list of strings, Lua will create a copy of it.
All other references to it will refer to this copy.
> If I push a string value onto the stack (e.g. lua_getglobal(L,
> “my_string”) ) does Lua duplicate the string or just use a reference to
> the original string?
If the string doesn't exist in the state, it will be created, otherwise, a
reference to the string in the Lua state is used.
> If I call lua_tostring (assuming the object is an actual string and not
> converted from a different type) does Lua return a pointer to the original
> string content or does it duplicate the string in a C-compatible manner
> and return a pointer to that?
It returns a pointer to a constant string. This will point to the
internal copy of the string Lua has, but will be NUL terminated.
> Given the above and assuming that I have a Lua global string “my_string”
> that is constant for the lifetime of the lua_State, is the following code
> safe or not?
> const char *str = luaL_checkstring(L, -1);
> lua_pop(L, 1);
> return str;
Technically no. References are only valid as long as they're on the
stack, or there exists a reference elsewhere in the Lua state. Since you
can't be sure if the string has another reference somewhere (in the general
case), popping the stack like this removes the reference to the string and
it could become sugject to garbage collection.