lua-users home
lua-l archive

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


On 12.11.21 14:37, ellie wrote:
> I'm wondering though, couldn't the lua_pushcfunction itself cause an out of
> memory error too?

According to the Lua manual the functions lua_pushcfunction,
lua_pushlightuserdata, lua_pcall and lua_touserdata are not raising memory errors.

So the only situation for the function ppushstring having memory problems is the
case that there are not enough free stack slots. The lua manual says: "you are
responsible for controlling stack overflow", i.e. you will have undefined
behaviour if there are not engough free slots on the stack.

>From the manual: "Whenever Lua calls C, it ensures that the stack has space for
at least LUA_MINSTACK extra elements... LUA_MINSTACK is defined as 20". In most
cases for simple C functions this is enough, but in more complicated cases, you
could call checkstack before the other memory allocation to assure that there is
enough space on the stack, e.g.:

luaL_checkstack(L, 5, NULL); // assures enough space on the stack
char *p = returns_some_allocated_thing();
if (!p) {
     lua_pushstring("out of memory");
     return lua_error(L);
}
int status = ppushstring(L, p);  // uses only stack slots
free(p);
if (status != LUA_OK) {
     return lua_error(L);
}
return 1;

Best regards,
Oliver