Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua memory management

Tags:

lua

How can we free the lua stack?

like image 776
Constantine Fry Avatar asked Aug 06 '09 11:08

Constantine Fry


People also ask

What is Lua memory?

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.

Why is there no garbage collector in C++?

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.


2 Answers

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

like image 161
Alexander Gladysh Avatar answered Sep 18 '22 12:09

Alexander Gladysh


Basically, the only way I know for freeing the whole lua stack is calling lua_close on the lua_State instance.

like image 33
Bluehorn Avatar answered Sep 18 '22 12:09

Bluehorn