How does Garbage Collection work in Lua Programming?


Lua provides automatic garbage collection that is very helpful in providing safe memory management. It basically means that you do not need to worry about the newly created object or how to allocate memory.

Lua is running a garbage collector to collect all dead objects (that is, objects that can not be accessed in Lua) to perform automatic memory management.

Lua also provides us with different functions that we can use to interact with the garbage collector, these functions are −

  • collectgarbage ( "collect") − returns a number that denotes whether the collector does a full garbage collection cycle.
  • collectgarbage ( "count") − returns the number of bytes total amount of memory used by Lua.
  • collectgarbage ( "restart") − restart the garbage collector.
  • collectgarbage ( "stop") − stop the garbage collector.

Now that we know what functions Lua provides us when it comes to garbage collectors, let’s explore a simple program where we will use some of these functions.

Example

Consider the example shown below −

 Live Demo

fruits = {"apple", "orange", "banana"}
print(collectgarbage("count"))
fruits = nil
print(collectgarbage("count"))
print(collectgarbage("collect"))
print(collectgarbage("count"))

Output

32.4208984375
32.4580078125
0
25.3154296875

It should be noted that the output may vary as it totally depends on the machine's internal architecture.

Updated on: 20-Jul-2021

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements