以下代碼將表格格式化爲可打印的字符串,但我覺得這樣做可以更容易。使用string.gsub格式化Lua中的表格
function printFormat(table)
local str = ""
for key, value in pairs(table) do
if value == 1 then
str = str .. string.gsub(value, 1, "A, ") -- Replaces 1 with A
elseif value == 2 then
str = str .. string.gsub(value, 2, "B, ") -- Replaces 2 with B
elseif value == 3 then
str = str .. string.gsub(value, 3, "C, ") -- Replaces 3 with C
elseif value == 4 then
str = str .. string.gsub(value, 4, "D, ") -- Replaces 4 with D
end
end
str = string.sub(str, 1, #str - 2) -- Removes useless chars at the end (last comma and last whitespace)
str = "<font color=\"#FFFFFF\">" .. str .. "</font>" -- colors the string
print(str)
end
local myTable = {1,4,3,2,3,2,1,3,4,2,2,...}
printFormat(myTable)
有沒有辦法使用oneliner而不是循環遍歷每個索引並進行更改?
還是讓代碼更緊湊?
'STR = table.concat(myTable的, ' '):GSUB(' %d +',{[ '1'] ='A',['2'] ='B',['3'] ='C',['4'] ='D'})' –