Lua Table 引用, 拷贝

    lua 除了简单类型分配内存外,table只是传递引用,所以不能用简单的 "=" 来copy两个表,并试图修改一个表中的值。

tb = {}
tb.a = 11
tb.b = 22
tb_ref = tb
function p(tip)
  print("--------------------------"  .. tip)
  print("tb.a = " .. tb.a .. "    " .. "tb.b = " .. tb.b)
  print("tb_ref.a = " .. tb_ref.a .. "    " .. "tb_ref.b" .. tb_ref.b)
end
p("原始")
tb_ref.a = 33
p("修改了引用的a = 33,原来的a也变了")
tb.b = 44
p("修改了原始的b = 44,引用的b也变了")
print("----------------------非表test")
a = 1
c = a
c = 3
print("a = " .. a)
print("c = " .. c) 

打印结果:
--------------------------原始
tb.a = 11    tb.b = 22
tb_ref.a = 11    tb_ref.b22
--------------------------修改了引用的a = 33,原来的a也变了
tb.a = 33    tb.b = 22
tb_ref.a = 33    tb_ref.b22
--------------------------修改了原始的b = 44,引用的b也变了
tb.a = 33    tb.b = 44
tb_ref.a = 33    tb_ref.b44
----------------------非表test
a = 1
c = 3

  1,当改变表的一个值以后,它的引用的值也发生了变化。

  2,对于非表的一般常数来说,它的赋值不存在引用的问题。

LuaTable的拷贝方法:

方法一:

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

方法二:

function deepcopy(object)
    local lookup_table = {}
    local function _copy(object)
        if type(object) ~= "table" then
            return object
        elseif lookup_table[object] then
            return lookup_table[object]
        end  -- if
        local new_table = {}
        lookup_table[object] = new_table
        for index, value in pairs(object) do
            new_table[_copy(index)] = _copy(value)
        end  -- for
        return setmetatable(new_table, getmetatable(object))
    end  -- function _copy
    return _copy(object)
end  -- function deepcopy

参考网址:

http://blog.sina.com.cn/s/blog_49bdd36d0100fdc1.html

http://www.360doc.com/content/13/1112/21/14605176_328731142.shtml

转载于:https://my.oschina.net/u/223340/blog/301668

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值