Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The differences between `lua_pushstring` and `lua_pushliteral`

Tags:

lua

As per the documentation(https://www.lua.org/manual/5.3/manual.html#lua_pushliteral), which says that: This macro is equivalent to lua_pushstring, but should be used only when s is a literal string.

But I can't understand the explanation aforementioned at all. As far as I can see, there is no difference from the the macro definition for lua_pushliteral:

#define lua_pushliteral(L, s) lua_pushstring(L, "" s)

like image 285
John Avatar asked Sep 03 '26 13:09

John


1 Answers

The documentation for lua_pushliteral in Lua 5.4 is the same as 5.3, except it adds "(Lua may optimize this case.)". So while it is currently the same as calling lua_pushstring, the Lua devs are giving themselves the option to optimize it in the future.

EDIT: As an example, the doc for lua_pushstring says:

Lua will make or reuse an internal copy of the given string, so the memory at s can be freed or reused immediately after the function returns.

But a C string literal is read-only, so it's impossible for the C code to free or reuse the memory. Also, Lua strings are immutable. It's basically useless to copy one immutable object to another immutable object when you could just refer to the same memory from both places. That means one possible way to optimize lua_pushliteral would be to just not make the copy that lua_pushstring does.

like image 165
luther Avatar answered Sep 05 '26 17:09

luther