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