2017-04-21 84 views
2

我想複製一個表作爲參考使用另一個變量。Table.copy用變量來命名錶

這是表:

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

淺複製

這是一個簡單的,天真的實施

+0

如果您將某些內容放在引號中,它是一個字符串?那麼tableofObjectTables [「a」] = aObjects呢?雖然我不知道科羅納,但不知道它是否有效。也許'aObjects'爲空,它在哪裏分配? – rotgers

回答

1

1)假設你宣佈當地aObjects,上述bObjects和其他表:

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

現在,你應該嘗試的工作

2)如果aObjectsbObjects全球你可以使用_G變量來訪問它們

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

完美的作品。謝謝。 – Atrag

0

try代碼。它只複製頂級價值及其直接子女;沒有深層次的兒童,metatables或特殊類型(如用戶數據或協同程序)的處理。它也容易受__pairs metamethod的影響。

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 

深複製

深拷貝複製所有級別(或級別的特定子集)。 這是一個簡單的遞歸實現,它另外處理metatables並避免__pairs metamethod。

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 

此外,它是遞歸的,這意味着它可能會溢出大型表的堆棧。

+0

謝謝,但這並沒有幫助。如果我做shallowcopy(tableofObjectTables [selectedLetter]),那麼它返回字符串aObject而不是複製aObject表。 – Atrag