--PrintTable.lua
local PrintTb = {}
local function _t_2string(depth)
local _t_str = ""
for i = 1, depth do
_t_str = _t_str .. " "
end
return _t_str
end
local function table_is_num_array(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
if type(k) ~= "number" or math.floor(k) ~= k then
return false
end
end
return count == #t
end
local function table_loop(t_string, t, depth, is_num_array)
for k, v in pairs(t) do
if type(k) == "number" and type(v) == "table" then
t_string = t_string .. _t_2string(depth) .. "["..tostring(k).."]".. " = "
t_string = t_string .. "{\n"
t_string = table_loop(t_string, v, depth + 1)
t_string = t_string .. _t_2string(depth) .. "},\n"
elseif type(v) == "table" then
t_string = t_string .. _t_2string(depth) .. tostring(k) .. " = "
t_string = t_string .. "{\n"
if table_is_num_array(v) then
t_string = t_string .. _t_2string(depth + 1)
end
t_string = table_loop(t_string, v, depth + 1, table_is_num_array(v))
if table_is_num_array(v) then
t_string = t_string .. "\n" .. _t_2string(depth) .. "},\n"
else
t_string = t_string .. _t_2string(depth) .. "},\n"
end
elseif type(v) == "boolean" then
t_string = t_string .. _t_2string(depth) .. "[\""..tostring(k).."\"]".. " = " .. tostring(v) .. ",\n"
elseif type(v) == "function" then
t_string = t_string .. _t_2string(depth) .. tostring(k).. " = function,\n"
else
if is_num_array then
t_string = t_string .. tostring(v) .. ","
else
t_string = t_string .. _t_2string(depth) .. k .. " = "
if type(v) == "string" then
t_string = t_string .. "\"" .. tostring(v) .. "\"" .. ",\n"
else
t_string = t_string .. tostring(v) .. ",\n"
end
end
end
end
return t_string
end
function PrintTb:print(t, name)
local str = "{\n"
str = table_loop(str, t, 1) .. "}\n"
print(name.." = "..str)
end
return PrintTb
将上述代码保存为一个lua文件,例如:PrintTable.lua, 使用示例:
--main.lua
local PrintTb = require("PrintTable")
local t = {
num = 10,
list = {1,2,3,4,54,5,6,76,7,801},
array = {{x = 1, y = 2, z = 3},{x = 10, y = 20, z = 30},{x = 100, y = 200, z = 300},},
test_info = {
info = {
id = 10000,
msg = "shiguangqingqianchu",
list = {"sdfa","werqwer","sfawerqwe"},
}
},
multi_t = {
multi_t1 = {
multi_t2 = {
multi_t3 = {
str = "hello lua!",
list = {1,23,3,4,5,56},
func = function(a, b)
return a + b
end
}
}
}
},
func = function(a, b)
return a + b
end
}
PrintTb:print(t, "t")
示例结果: