Table.copy 用变量命名 table

Table.copy with variable to name the table

我想使用另一个变量作为参考来复制 table。

这是table:

local tableofObjectTables = { }
tableofObjectTables["a"] = "aObjects"
tableofObjectTables["b"] = "bObjects"
tableofObjectTables["c"] = "cObjects"
tableofObjectTables["d"] = "dObjects"

这是我的尝试:

local selectedLetter = "a"
local tabletoCopy1 = tableofObjectTables[selectedLetter]
     activeObjects = table.copy(tabletoCopy1)

tabletoCopy 是 "aObjects"。 ActiveObjects = table.copy(aObjects) 工作正常。

谢谢。

尝试来自 http://lua-users.org

的代码

浅拷贝

这是一个简单、天真的实现。它只复制顶级值及其直接children;没有处理更深层次的 children、元表或特殊类型,如用户数据或协程。它也容易受到 __pairs 元方法的影响。

function shallowcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in pairs(orig) do
            copy[orig_key] = orig_value
        end
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

深拷贝

深拷贝复制所有级别(或级别的特定子集)。 这是一个简单的递归实现,它额外处理元表并避免使用 __pairs 元方法。

function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

此外,它是递归的,这意味着它可能会溢出大表的堆栈。

1) 假设您在上面声明了 local aObjectsbObjects 和其他表:

local tableofObjectTables = { }
-- store reference to objects table rather than string
tableofObjectTables["a"] = aObjects 
tableofObjectTables["b"] = bObjects 
--more declarations here

现在你的尝试应该可以了

2) 如果 aObjectsbObjectsglobal 表,您可以使用 _G访问它们的变量

local tableNameToCopy = tableofObjectTables[selectedLetter]
activeObjects = table.copy(_G[tableNameToCopy])