http://blog.sina.com.cn/s/blog_49bdd36d0100fdc1.html
lua 除了简单类型分配内存外,table只是传递引用,所以不能用简单的"="来copy两个表,并试图修改一个表中的值。
用以下方法实现table copy:
1.
function th_table_dup(ori_tab)
if (type(ori_tab) ~= "table") then
return nil;
end
local new_tab = {};
for i,v in pairs(ori_tab) do
local vtyp = type(v);
if (vtyp == "table") then
new_tab[i] = th_table_dup(v);
elseif (vtyp == "thread") then
-- TODO: dup or just point to?
new_tab[i] = v;
elseif (vtyp == "userdata") then
-- TODO: dup or just point to?
new_tab[i] = v;
else
new_tab[i] = v;
end
end
return new_tab;
end
if (type(ori_tab) ~= "table") then
return nil;
end
local new_tab = {};
for i,v in pairs(ori_tab) do
local vtyp = type(v);
if (vtyp == "table") then
new_tab[i] = th_table_dup(v);
elseif (vtyp == "thread") then
-- TODO: dup or just point to?
new_tab[i] = v;
elseif (vtyp == "userdata") then
-- TODO: dup or just point to?
new_tab[i] = v;
else
new_tab[i] = v;
end
end
return new_tab;
end
2.
This function returns a deep copy of a given table. The function below also copies the metatable to the new table if there is one, so the behaviour of the copied table is the same as the original. But the 2 tables share the same metatable, you can avoid this by changing this 'getmetatable(object)' to '_copy( getmetatable(object) )'.
转载于:https://blog.51cto.com/zgame/1151809