在lua脚本中,table是一个基本的数据类型,它类似于结构体和类,包含各种属性,同时一个table也有类似于指针的特性:
local tSrc={color="blue"}
local tDst=tSrc
tSrc.color = "red"
print(tDst.color) -- 得到的是 red
由于项目需要,对一个较多属性的table tOld进行复制,且tOld的属性不能被改变,而被复制出来的新table tNew的属性将会频繁变动。lua本身不支持table复制,网上找了一个别人写的函数:
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

订阅HenryXu的更新(RSS)