zc5872061

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1、普通垃圾回收

--lua弱表,主要是删除key或者value是table的一种元方法  
--元表里的__mode字段包含k或者v;k表示key为弱引用;v表示value为弱引用  
  
local testa = {}  
tbl_key = {}  
testa[tbl_key] = 1  
tbl_key = {}  
testa[tbl_key] = 2  
  
--垃圾回收  
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 === 1  
table: 004FB8E0 === 2  
>Exit code: 0  

2、设置弱引用为key

local testa = {}  
local mt = {__mode = 'k'}  
setmetatable(testa,mt)  
  
tbl_key = {}  
testa[tbl_key] = 1  
tbl_key = {}  
testa[tbl_key] = 2  
  
--垃圾回收  
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 === 2  
>Exit code: 0  

通过key的弱引用,覆盖了key为key_table的值;没有其他地方在引用,所以被回收掉了

 

3、设置弱引用为value

local testa = {}  
local mt = {__mode = 'v'}  
setmetatable(testa,mt)  
  
tbl_key = {1,2,3}  
testa[1] = tbl_key  
tbl_key = {4,5,6}  
testa[2] = 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=== 4
 value=== 5
 value=== 6
>Exit code: 0

转载:http://blog.csdn.net/u012071200/article/details/31400541

posted on 2016-11-29 00:07  人生HighHigh  阅读(665)  评论(0编辑  收藏  举报