【问题标题】:Copying a tables values in Lua is changing the originals value在 Lua 中复制表值正在更改原始值
【发布时间】:2021-01-13 01:49:34
【问题描述】:

我想复制一个简单的表格,但是每当我更改复制的表格时,它也会改变原始表格,这很奇怪

function tablelength(T)
  local count = 0
    for _ in pairs(T) do count = count + 1 end
  return count
end

board = {}
print("board: "..tablelength(board))

newBoard = board
newBoard[tablelength(newBoard) + 1] = 1
print("board: "..tablelength(board))
newBoard[tablelength(newBoard) + 1] = 1
print("board: "..tablelength(board))

输出:

board: 0
board: 1
board: 2

【问题讨论】:

    标签: arrays lua


    【解决方案1】:

    newBoard = board 仅创建了一个新的引用 newBoard,在 board 之后第二个,指向由 {} 创建的同一个表。

    如果你想要一个新表,你需要深拷贝一个表。

    类似这样的:

    local function deep_copy( tbl )
        local copy = {}
        for key, value in pairs( tbl ) do
            if type( value ) ~= 'table' then
                copy[key] = value
            else
                copy[key] = deep_copy( value )
            end
        end
        return copy
    end
       
    

    这是一个简单的实现,它不会复制元表和作为表的键(在 Lua 中可能),以及包含对自身的引用的表,但对于您的目的来说这可能已经足够了。

    延伸阅读:https://www.lua.org/pil/2.5.html,从第二段开始。

    P.S.基于http://lua-users.org/wiki/CopyTable的不那么天真的实现:

    local function deep_copy( original, copies )
        if type( original ) ~= 'table' then return original end
    
        -- original is a table.
        copies = copies or {} -- this is a cache of already copied tables.
    
        -- This table has been copied previously.
        if copies[original] then return copies[original] end
        
        -- We need to deep copy the table not deep copied previously.
        local copy = {}
        copies[original] = copy -- store a reference to copied table in the cache.
        for key, value in pairs( original ) do
            local dc_key, dc_value = deep_copy( key, copies ), deep_copy( value, copies )
            copy[dc_key] = dc_value
        end
        setmetatable(copy, deep_copy( getmetatable( original ), copies) )
        return copy
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 2013-11-01
      • 2022-01-21
      • 2021-12-30
      • 1970-01-01
      • 2019-09-13
      • 2013-02-08
      相关资源
      最近更新 更多