3.7 – Controlling Garbage Collection

Lua uses two numbers to control its garbage collection: the count and the threshold (see 2.9). The first counts the amount of memory in use by Lua; when the count reaches the threshold, Lua runs its garbage collector. After the collection, the count is updated and the threshold is set to twice the count value.

You can access the current values of these two numbers through the following functions:

  1. int lua_getgccount (lua_State *L);
  2. int lua_getgcthreshold (lua_State *L);

Both return their respective values in Kbytes. You can change the threshold value with

  1. void lua_setgcthreshold (lua_State *L, int newthreshold);

Again, the newthreshold value is given in Kbytes. When you call this function, Lua sets the new threshold and checks it against the byte counter. If the new threshold is less than the byte counter, then Lua immediately runs the garbage collector. In particular lua_setgcthreshold(L,0) forces a garbage collection. After the collection, a new threshold is set according to the previous rule.