一般來說,連接任意表的概念在Lua中沒有意義,因爲單個鍵只能有一個值。
有些特殊情況下級聯確實有意義。其中之一就是包含簡單數組的表格,這可能是返回結果列表的函數的自然結果。
在這種情況下,你可以寫:
-- return a new array containing the concatenation of all of its
-- parameters. Scaler parameters are included in place, and array
-- parameters have their values shallow-copied to the final array.
-- Note that userdata and function values are treated as scalar.
function array_concat(...)
local t = {}
for n = 1,select("#",...) do
local arg = select(n,...)
if type(arg)=="table" then
for _,v in ipairs(arg) do
t[#t+1] = v
end
else
t[#t+1] = arg
end
end
return t
end
這是一個淺拷貝,並沒有試圖找出一個userdata
或函數值,可能需要不同的某種類型的容器或對象治療。
另一種實現可能會修改第一個參數,而不是創建一個新表。這樣可以節省複製的成本,並且使得array_concat
與..
運算符在字符串上不同。
編輯:正如Joseph Kingry在評論觀察,我沒能正確地從...
提取每個參數的實際值。我也沒有從函數返回合併表。這就是我在答案框中編寫代碼而不是測試代碼。
可能欺騙:http://stackoverflow.com/questions/1283388/lua-merge-tables。 你提到「循環中的遞歸」。你搜索一個深度複製+合併? – gimpf 2009-09-11 14:00:45
以下是我發現提供的解決方案的鏈接: http://ardoris.wordpress.com/2008/08/10/lua-merge-two-tables-awesome3-rc2-config/ http:// www.idevgames.com/forum/archive/index.php/t-10223.html 雖然我理解每種方法,但似乎都不起作用。你有沒有工作解決方案? – 2009-09-11 15:09:17
gimpf,也許我不完全清楚。合併表格和合並表格是相似的,但是非常不同。我有興趣將一個表追加到另一個表中,因此使用了concatenate這個詞。 – 2009-09-11 15:16:07