天天看點

lua實作深度拷貝table表

lua當變量作為函數的參數進行傳遞時,類似的也是boolean,string,number類型的變量進行值傳遞。而table,function,userdata類型的變量進行引用傳遞。故而當table進行指派操作之時,table A

指派給table B,對表B中元素進行操作自然也會對A産生影響,當然對B表本身進行處理例如B =nil或者将表B指向另一個表,則對A是沒什麼影響的;下面即是對lua table的深度拷貝。

deepcopy = function(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
        local new_table = {}
        lookup_table[object] = new_table
        for index, value in pairs(object) do
            new_table[_copy(index)] = _copy(value)
        end
        return setmetatable(new_table, getmetatable(object))
    end

    return _copy(object)
end

local testA =  {1,2,3,4,5}

local testB = testA
testB[2] = "我擦"

local testC = deepcopy(testA)
testC[2] = "我勒個去"

for k , v  in ipairs (testA) do
    print("testA",k, v )
end

print("============================")

for k , v  in ipairs (testC) do
    print("testC",k, v )
end      

運作結果如下:

testA 1 1

testA 2 我擦

testA 3 3

testA 4 4

testA 5 5

============================

testC 1 1

testC 2 我勒個去

testC 3 3

testC 4 4

testC 5 5

lua實作深度拷貝table表
lua實作深度拷貝table表

繼續閱讀