lua-users home
lua-l archive

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


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

There's no need to worry about the Lua side because it uses
internalization for short strings, which are most of the cases of
everyday use in the C API.

See: https://github.com/lua/lua/blob/master/lstring.c#L198

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

See https://github.com/lua/lua/blob/6aeaeb5656a006ad95b35dd7482798fdc5f02f5e/lstring.c#L251

Pedro