1、普通垃圾回收
--lua弱表,主要是删除key或者value是table的一种元方法
--元表里的__mode字段包含k或者v;k表示key为弱引用;v表示value为弱引用 local testa = {}
tbl_key = {}
testa[tbl_key] =
tbl_key = {}
testa[tbl_key] = --垃圾回收
collectgarbage() local function PrintInfo() for k, v in pairs(testa) do
print(k, "===", v)
end end PrintInfo()
显示结果:
>lua -e "io.stdout:setvbuf 'no'" "Lua.lua"
table: 004FB890 ===
table: 004FB8E0 ===
>Exit code:
2、设置弱引用为key
local testa = {}
local mt = {__mode = 'k'}
setmetatable(testa,mt) tbl_key = {}
testa[tbl_key] =
tbl_key = {}
testa[tbl_key] = --垃圾回收
collectgarbage() local function PrintInfo() for k, v in pairs(testa) do
print(k, "===", v)
end end PrintInfo()
显示结果:
>lua -e "io.stdout:setvbuf 'no'" "Lua.lua"
table: 006EB930 ===
>Exit code:
通过key的弱引用,覆盖了key为key_table的值;没有其他地方在引用,所以被回收掉了
3、设置弱引用为value
local testa = {}
local mt = {__mode = 'v'}
setmetatable(testa,mt) tbl_key = {,,}
testa[] = tbl_key
tbl_key = {,,}
testa[] = tbl_key --垃圾回收
collectgarbage() local function PrintInfo() for k, v in pairs(testa) do
for key, value in pairs(v) do
print(" value===", value)
end
end end PrintInfo()
结果:
>lua -e "io.stdout:setvbuf 'no'" "Lua.lua"
value===
value===
value===
>Exit code:
转载:http://blog.****.net/u012071200/article/details/31400541