SoFunction
Updated on 2025-04-08

Introduction to weak quotes in Lua

The weak reference type of a table is determined by the __mode field in its element table. The value of this field should be a string. If the string contains the letter 'k'/'v', then the value of this table is a weak reference. The code is as follows:

Copy the codeThe code is as follows:

key = {} 
a[key] = 1 
key = {} 
a[key] = 2 
collectgarbage() -- Forced garbage collection
for k, v in pairs(a) do 
    print(v) 
end 

Results: 2

The second sentence copying key = {} will overwrite the first key. When the collector is running, since nowhere else is referencing the first key, the first key is recycled, and the corresponding entry in the table is also deleted. As for the second key, the variable key still references it, so it is not recycled.

Note that lua will only recycle objects in weak reference tables, while values ​​like numbers and bools cannot be recycled.