使用string.gsub在Lua中格式化表

时间:2015-08-09 13:59:27

标签: lua formatting gsub lua-table

以下代码将表格格式化为可打印字符串,但我觉得这样做可以轻松完成。

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

或者让代码更紧凑?

2 个答案:

答案 0 :(得分:0)

您可以使用帮助程序表替换多个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 :(得分:0)

  1. 使用table.concat
  2. string.gsub可以使用替换表执行替换。
  3. 不要使用function printFormat( tInput ) local sReturn = table.concat( tInput, ', ' ) sReturn = sReturn:gsub( '%d', {['1'] = 'A', ...} ) -- update table accordingly return '<font color="#FFFFFF">' .. str .. "</font>" end 之类的名称作为您自己的变量。
  4. 因此:

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

    并且,对于一个班轮:

    {{1}}
相关问题