The Lua Garbage Collector

Introduction

In Lua there exists a function called collectgarbage(). This function can be used to manually clear the memory used by a channel script’s variables and processes, and also to provide useful information about how much memory a process may use.

Task [top]

Explain how to use the collectgarbage() function for memory management.

Implementation [top]

The collectgarbage ([opt [, arg]]) function performs different functions according to its first argument, opt. depending on where you call the function in your translator script, the collector can return different information that could be useful for:

  • Debugging code
  • Finding memory leaks
  • Memory management
  • Writing efficient code

How it works [top]

This section explains how the Pause and Step Multiplier settings affect garbage collections, and what each value of the opt parameter for the collectgarbage() function does.

Pause:

The garbage-collector pause controls how long the collector waits before starting a new cycle. Larger values make the collector less aggressive. Values smaller than 100 mean the collector will not wait to start a new cycle. The default value of 200 means that the collector waits for the total memory in use to double before starting a new cycle.

Step multiplier:

The step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. Values smaller than 100 make the collector too slow and may result in the collector never finishing a cycle (which can slow down or freeze a program). The default value of 200 means that the collector runs at “twice” the speed of memory allocation.

Values for the ‘opt’ parameter:

  • stop: stops the garbage collector.
  • restart: restarts the garbage collector.
  • collect: performs a full garbage-collection cycle.
  • count: returns the total memory in use by Lua (in Kbytes).
  • step: performs a garbage-collection step.

    The step “size” is controlled by arg (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of arg. Returns true if the step finished a collection cycle.

  • setpause: sets arg as the new value for the pause of the collector. Returns the previous value for pause.
  • setstepmul: sets arg as the new value for the step multiplier of the collector. Returns the previous value for step.

Note: Tuning of the garbage collection parameters should be undertaken with caution. You will need to experiment until you find out what works best for your circumstances (which may also vary from program to program).

More information [top]

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.