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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM