用 string.gsub 格式化 Lua 中的 table

Formatting a table in Lua with string.gsub

以下代码将 table 格式化为 printable 字符串,但我觉得这样做可以更容易。

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 而不是遍历每个索引并进行更改?

或者让代码更紧凑?

您可以使用助手 table 来替换多个 if 语句:

local chars = {"A", "B", "C", "D"}
for _, v in ipairs(t) do
    str = str .. chars[v] .. ", "
end

或者,如果有超过 14,试试这个:

for _, v in ipairs(t) do
    str = str .. string.char(string.byte('A') + v) .. ", "
end
  1. 使用table.concat.
  2. string.gsub可以使用替换table.
  3. 进行替换
  4. 不要为您自己的变量使用 table 这样的名称。

因此:

function printFormat( tInput )
    local sReturn = table.concat( tInput, ', ' )
    sReturn = sReturn:gsub( '%d', {['1'] = 'A', ...} ) -- update table accordingly
    return '<font color="#FFFFFF">' .. str .. "</font>"
end

并且,对于一个班轮:

return '<font color="#FFFFFF">' .. ( table.concat(tInput, ', ') ):gsub( '%d', {['1'] = 'A', ...}  )