lua 除了简单类型分配内存外,table只是传递引用,所以不能用简单的 "=" 来copy两个表,并试图修改一个表中的值。
1tb = {} 2tb.a = 11 3tb.b = 22 4tb_ref = tb 5function p(tip) 6 print("--------------------------" .. tip) 7 print("tb.a = " .. tb.a .. " " .. "tb.b = " .. tb.b) 8 print("tb_ref.a = " .. tb_ref.a .. " " .. "tb_ref.b" .. tb_ref.b) 9end 10p("原始") 11tb_ref.a = 33 12p("修改了引用的a = 33,原来的a也变了") 13tb.b = 44 14p("修改了原始的b = 44,引用的b也变了") 15print("----------------------非表test") 16a = 1 17c = a 18c = 3 19print("a = " .. a) 20print("c = " .. c) 21 22打印结果: 23--------------------------原始 24tb.a = 11 tb.b = 22 25tb_ref.a = 11 tb_ref.b22 26--------------------------修改了引用的a = 33,原来的a也变了 27tb.a = 33 tb.b = 22 28tb_ref.a = 33 tb_ref.b22 29--------------------------修改了原始的b = 44,引用的b也变了 30tb.a = 33 tb.b = 44 31tb_ref.a = 33 tb_ref.b44 32----------------------非表test 33a = 1 34c = 3
1,当改变表的一个值以后,它的引用的值也发生了变化。
2,对于非表的一般常数来说,它的赋值不存在引用的问题。
LuaTable的拷贝方法:
方法一:
1function th_table_dup(ori_tab) 2 if (type(ori_tab) ~= "table") then 3 return nil; 4 end 5 local new_tab = {}; 6 for i,v in pairs(ori_tab) do 7 local vtyp = type(v); 8 if (vtyp == "table") then 9 new_tab[i] = th_table_dup(v); 10 elseif (vtyp == "thread") then 11 -- TODO: dup or just point to? 12 new_tab[i] = v; 13 elseif (vtyp == "userdata") then 14 -- TODO: dup or just point to? 15 new_tab[i] = v; 16 else 17 new_tab[i] = v; 18 end 19 end 20 return new_tab; 21end
方法二:
1function deepcopy(object) 2 local lookup_table = {} 3 local function _copy(object) 4 if type(object) ~= "table" then 5 return object 6 elseif lookup_table[object] then 7 return lookup_table[object] 8 end -- if 9 local new_table = {} 10 lookup_table[object] = new_table 11 for index, value in pairs(object) do 12 new_table[_copy(index)] = _copy(value) 13 end -- for 14 return setmetatable(new_table, getmetatable(object)) 15 end -- function _copy 16 return _copy(object) 17end -- function deepcopy
参考网址:
http://blog.sina.com.cn/s/blog_49bdd36d0100fdc1.html
http://www.360doc.com/content/13/1112/21/14605176_328731142.shtml