Lua Table.copy使用变量命名表

Lua Table.copy使用变量命名表,lua,coronasdk,Lua,Coronasdk,我想使用另一个变量作为引用复制一个表 这是表格: local tableofObjectTables = { } tableofObjectTables["a"] = "aObjects" tableofObjectTables["b"] = "bObjects" tableofObjectTables["c"] = "cObjects" tableofObjectTables["d"] = "dObjects" 这是我的尝试: local selectedLetter = "a" local

我想使用另一个变量作为引用复制一个表

这是表格:

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是“对象”
ActiveObjects=table.copy(aoobjects)
工作正常

谢谢。

请从中尝试代码

浅拷贝

这是一个简单、幼稚的实现。它只复制顶级值及其直接子级;不需要处理更深层次的子级、元表或特殊类型,如用户数据或协同路由。它也容易受到_配对元方法的影响

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
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
深度复制

深度副本复制所有级别(或级别的特定子集)。 下面是一个简单的递归实现,它额外处理元表并避免_对元方法

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
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
aoobjects
boobjects
和上面的其他表:

local tableofObjectTables = { }
-- store reference to objects table rather than string
tableofObjectTables["a"] = aObjects 
tableofObjectTables["b"] = bObjects 
--more declarations here
现在你的尝试应该奏效了

2)如果
aoobjects
boobjects
全局的表,您可以使用
变量访问它们

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

如果你在引号中加上什么,它就是一个字符串?tableofObjectTables[“a”]=aObjects怎么样?我不知道科罗纳,不知道它是否有效。可能
aObjects
为空,在哪里分配了它?谢谢,但这没有帮助。如果我进行浅复制(tableofObjectTables[selectedLetter]),那么它将返回字符串AOObject,而不是复制AOObject表。工作正常。非常感谢。