google code prettify

2019年11月30日 星期六

【Lua】table to string

A lua function which converts tables to text is required in many cases.
A common use case is writing tables to a file as a configuration and reloading it.
Readability of output tables is a consideration for debugging and analysis.

function tab2str(t, i)
    if type(t) == "string" then -- enum string and eval all names to tables
        local s = ""
        for i in t:gmatch("[^|]+") do s = s..i.."="..i.."," end
        t = load("return {"..s:sub(1, -2).."}")()
    end

    local n, f = 0, true -- number of table entry, indent flag
    local s, i = "", i and i or "" -- result string and indent
    for _ in pairs(t) do n = n + 1 end -- count entries

    for k, v in pairs(t) do
        local c = n > 1 and true or false -- comma
        if f then s = s..i f = false end
        s = s..k.."="

        if type(v) == "table" then
            c = c and (i == "" and "\n" or ",\n") or ""
            s = s.."{\n"..tab2str(v, i.."  ").."\n"..i.."}"..c
            f = true
        else
            s = s..v..(c and ", " or "")
        end
        n = n - 1
    end
    return s
end

Example:

k = { k1=1, k2=2, k3={"k"} }
t = { t1=1, t2=2, {"t"} }

print(tab2str("k")) -- identical to print(tab2str({k=k}))
print()
print(tab2str("k|t")) -- identical to print(tab2str({k=k,t=t}))

Result:

k={
  k1=1, k2=2, k3={
    1=k
  }
}

t={
  1={
    1=t
  },
  t2=2, t1=1
}
k={
  k1=1, k2=2, k3={
    1=k
  }
}

沒有留言:

張貼留言