zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [转] css3变形属性transform
    [转] ReactJS之JSX语法
    [转] 那些在使用webpack时踩过的坑
    [转] jQuery的deferred对象详解
    [转] Webpack-CommonsChunkPlugin
    [转] 用webpack的CommonsChunkPlugin提取公共代码的3种方式
    Refs & DOM
    [转] Webpack的devtool和source maps
    [转] 编译输出文件的区别
    GDB && QString
  • 原文地址:https://www.cnblogs.com/jadeboy/p/3991661.html
Copyright © 2011-2022 走看看