导航

Henry Xu

大江东去,浪淘尽,千古风流人物。故垒西边,人道是,三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰!

« 程序员笑话一则

lua中的table复制

在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

 

lua_table_copy.lua

  • 相关文章:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-Blog .Theme from Google黑板报 By Washun Modified By Henry Xu

www.henryxu.com © 2007-2008 All Rights Reserved

浙ICP备07505342号

搜索本站

控制面板

最新评论及回复

最近发表