打印 Lua table 并连接字符串

Print the Lua table and connect the strings

我要打印table,比较复杂。像这样:

我不知道如何检查 table 中的每个值等于并连接这样的字符串 (value1, value2, value3, and value4) 在它结束之前,它必须以 and[=17 结束=]

Table:

table = {
 {amount = 1, items = "item1"},
 {amount = 1, items = "item2"},
 {amount = 1, items = "item3"},
 {amount = 2, items = "item4"},
 {amount = 3, items = "item5"},
}

P.S 我也需要对它们进行排序。 table.sort(table, function(a,b) return a.amount < b.amount end)

但我仍然坚持使用上面提到的连接字符串。

我希望它这样输出:

3x item5
2x item4
1x item1, item2, and item3

感谢您的回答,我是 Lua 的新手,英语不是我的母语。抱歉,语法和单词不正确。

解决方案是这样的,只是 item2, and item3 之间没有 and 的输出:

local t = {
 {amount = 1, items = "item1"},
 {amount = 1, items = "item2"},
 {amount = 1, items = "item3"},
 {amount = 2, items = "item4"},
 {amount = 3, items = "item5"},
}

local res = {}

for k,v in pairs(t) do
   res[v.amount] = res[v.amount] and (res[v.amount] .. ', ' .. v.items) or v.items  -- use ternary operator   
end 

for k,v in pairs(res) do 
   v = v:gsub("(.*), (.-)","%1 and %2")
   print(k,v)
end