table 转字符串

table 转字符串辅助类 TableAux

---@class table 的辅助
local TableAux = {}
local self = TableAux

---------------- table转字符串 ----------------
local function PrintSpace(p, count)
    for ii = 1, count do
        p("    ")
    end
end

local function PrintTable2(o, f, b, deep)
    p = f or io.write
    b = b or false

    if type(f) ~= "function" and f ~= nil then
        p(string.format("expected second argument %s is a function", tostring(f)))
    end
    if type(b) ~= "boolean" and b ~= nil then
        p(string.format("expected third argument %s is a boolean", tostring(b)))
    end

    if type(o) == "number" or type(o) == "function" or type(o) == "boolean" or type(o) == "nil" then
        p(tostring(o))
    elseif type(o) == "string" then
        p(string.format("%q", o))
    elseif type(o) == "table" then
        p("\n")
        PrintSpace(p, deep)
        p("{\n")
        for k, v in pairs(o) do
            PrintSpace(p, deep)
            if b then
                p("[")
            end
            PrintTable2(k, p, b, deep + 1)
            if b then
                p("]")
            end
            p(" = ")
            PrintTable2(v, p, b, deep + 1)
            p(",\n")
        end
        PrintSpace(p, deep)
        p("}")
    end
end

--- table转字符串 用于调试输出
--- @return string
function TableAux.TableToString(t)
    local printTabStr = ""
    PrintTable2(
        t,
        function(str)
            printTabStr = printTabStr .. str
        end,
        true,
        0
    )
    if printTabStr == "" then
    --print("LuaUtil.PrintTable printTabStr is nil")
    end
    return printTabStr
    --print(printTabStr)
end
---------------- table转字符串 ----------------

--- 获取table元素个数
--- @return number
function TableAux.TableCount(t)
    local num = 0
    if type(t) == "table" then
        for k, v in pairs(t) do
            num = num + 1
        end
    end
    return num
end

-- _G.TableAux = TableAux
return TableAux

测试代码

local TablaAux = require "TableAux"

local ta = {
    {a = 22, b = 1},
    {a = 100, b = 2},
    {a = 99, b = 3},
    {a = 44, b = 4},
    {a = 44, b = 5},
    {a = 44, b = 6},
    {a = 65, b = 7},
    {a = 78, b = 8},
    {a = 19, b = 9},
    {a = 22, b = 10},
    {a = 62, b = 11}
}

print("---输出tabal")
print(TablaAux.TableToString(ta))

 输出结果

{
[1] = 
    {
    ["a"] = 22,
    ["b"] = 1,
    },
[2] =
    {
    ["a"] = 100,
    ["b"] = 2,
    },
[3] =
    {
    ["a"] = 99,
    ["b"] = 3,
    },
[4] =
    {
    ["a"] = 44,
    ["b"] = 4,
    },
[5] =
    {
    ["a"] = 44,
    ["b"] = 5,
    },
[6] =
    {
    ["a"] = 44,
    ["b"] = 6,
    },
[7] =
    {
    ["a"] = 65,
    ["b"] = 7,
    },
[8] =
    {
    ["a"] = 78,
    ["b"] = 8,
    },
[9] =
    {
    ["a"] = 19,
    ["b"] = 9,
    },
[10] =
    {
    ["a"] = 22,
    ["b"] = 10,
    },
[11] =
    {
    ["a"] = 62,
    ["b"] = 11,
    },
}

猜你喜欢

转载自blog.csdn.net/ZFSR05255134/article/details/123848580