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 −
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.
Consider the example shown below −
fruits = {"apple", "orange", "banana"} print(collectgarbage("count")) fruits = nil print(collectgarbage("count")) print(collectgarbage("collect")) print(collectgarbage("count"))
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.