Reputation: 3044
Is there a way to make Lua to collect garbage more frequently?
It seems Lua hardly frees garbages in my app so the memory rises really high (over 500MB). The memory rises quickly especially when I declare many variables inside a large loop.
I know I can manually call collectgarbage()
but people say I should almost never call this function.
Therefore I wonder if there's any option to make the garbage collector to automatically run more frequently.
ADDED: if there's no way to do this, I would like to know if it's possible to get the memory usage in Lua so I can call collectgarbage()
when needed.
Upvotes: 2
Views: 2279
Reputation: 48196
You can use collectgarbage
to tune the GC. passing "setpause" or "setstepmul" as first param lets you tune the parameters.
"setpause" controls how much memory has to be allocated before it starts a new cycle. a value of 100 means it will run every allocation and a value of 200 means it will wait until memory doubles.
"setstepmul" controls how "fast" it tries to collect garbage.
If you pass "count" to collectgarbage
it will return the memory used in kilobytes.
On the C api side of things you use int lua_gc(lua_State *L, int what, int data)
and pass LUA_GCSETPAUSE
, LUA_GCSETSTEPMUL
as what for the tuning and passing LUA_GCCOUNT
as what
will return the memory used.
Upvotes: 3