How can we free the lua stack?
Lua uses automatic memory management that uses garbage collection based on certain algorithms that is in-built in Lua. As a result of automatic memory management, as a developer − No need to worry about allocating memory for objects. No need to free them when no longer needed except for setting it to nil.
C++ was built with competitors in mind that did not have garbage collection. Efficiency was the main concern that C++ had to fend off criticism from in comparison to C and others. If you want it you can use it, if you don't want it you aren't forced into using it.
Why do you want to do this?
If you need to remove all elements in Lua stack, you should call lua_settop(L, 0)
. To quote manual:
void lua_settop (lua_State *L, int index);
Accepts any acceptable index, or 0, and sets the stack top to this index. If the new top is larger than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed.
This would subject all elements in stack to garbage collection. Call lua_gc(LUA_GC_COLLECT)
afterwards to do garbage collection. If you really need to collect all collectable garbage, call it in a loop, until value, returned by lua_gc(LUA_GCCOUNT)
, would stay the same.
Note that (AFAIK) you can't free space, allocated for the stack itself — unless, of course, you call lua_close()
.
Basically, the only way I know for freeing the whole lua stack is calling lua_close on the lua_State instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With