[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Avoiding string duplication
- From: Chris Smith <space.dandy@...>
- Date: Tue, 5 Nov 2019 14:49:48 +0000
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.
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?
const char *str = luaL_checkstring(L, -1);
lua_pop(L, 1);
return str;
Regards,
Chris
—
Chris Smith <space.dandy@icloud.com>