Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Garbage Collection

Lua Garbage Collection

Lua uses automatic memory management. This means you don't have to worry about how the memory needed for newly created objects is allocated, nor about how to release the memory occupied by objects when they are no longer used.

Lua runs agarbage collectorto collect alldead objects (i.e., objects that can no longer be accessed in Lua) to accomplish automatic memory management. All memory used in Lua, such as strings, tables, userdata, functions, threads, internal structures, etc., is subject to automatic management.

Lua implements an incremental mark-and-sweep collector. It uses two numbers to control the garbage collection cycle: the garbage collector pause and the garbage collector step multiplier. Both numbers are expressed as percentages (for example, a value of 100 is represented internally as 1).

The garbage collector pause controls how long the collector waits before starting a new cycle. Increasing this value makes the collector less aggressive. When this value is less than 100, the collector does not wait before starting a new cycle. Setting this value to 200 makes the collector wait until total memory usage reaches twice the previous amount before starting a new cycle.

The garbage collector step multiplier controls the ratio of the collector's operating speed to the memory allocation speed. Increasing this value not only makes the collector more aggressive, but also increases the length of each incremental step. Do not set this value below 100, because then the collector would work too slowly to ever complete a cycle. The default value is 200, which means the collector works at "twice" the speed of memory allocation.

If you set the step multiplier to a very large number (10% larger than the number of bytes your program might use), the collector behaves like a stop-the-world collector. If you then set the pause to 200, the collector behaves like older versions of Lua: a full collection is performed each time the memory used by Lua doubles.


Garbage collector functions

Lua provides the following function **collectgarbage ([opt [, arg]])** to control automatic memory management:

The following demonstrates a simple garbage collection example:

Example

mytable

=

{

"apple"

,

"orange"

,

"banana"

}

print

(

collectgarbage

(

"count"

)

)

mytable

=

nil

print

(

collectgarbage

(

"count"

)

)

print

(

collectgarbage

(

"collect"

)

)

print

(

collectgarbage

(

"count"

)

)

After executing the above program, the output is as follows (note the changes in memory usage):



20.9560546875

20.9853515625

0

19.4111328125