在调试lua代码的时候,经常需要看table里的内容,这时候一般都是将打印table的方法放到工具模块中,方便调用。
现在写一个简单的工具模块
util.lua
local util = {}
local function get_type_first_print( t )
local str = type(t)
return string.upper(string.sub(str, 1, 1))..":"
end
function util.dump_table(t, prefix, indent_input, print)
local indent = indent_input
if indent_input == nil then
indent = 1
end
if print == nil then
print = _G["print"]
end
local p = nil
local formatting = string.rep(" ", indent)
if prefix ~= nil then
formatting = prefix .. formatting
end
if t == nil then
print(formatting.." nil")
return
end
if type(t) ~= "table" then
print(formatting..get_type_first_print(t)..tostring(t))
return
end
local output_count = 0
for k,v in pairs(t) do
local str_k = get_type_first_print(k)
if type(v) == "table" then
print(formatting..str_k..k.." -> ")
util.dump_table(v, prefix, indent + 1,print)
else
print(formatting..str_k..k.." -> ".. get_type_first_print(v)..tostring(v))
end
output_count = output_count + 1
end
if output_count == 0 then
print(formatting.." {}")
end
end
return util
测试代码:
local util = require "util"
--_G["print"] = function () end
local testTable = {"hello", "world", ["first"] = 1, ["second"] = 2}
util.dump_table(testTable, "--testTable")
输出结果:
--testTable N:1 -> S:hello
--testTable N:2 -> S:world
--testTable S:first -> N:1
--testTable S:second -> N:2
如果最后一行改成:
util.dump_table(testTable)
则输出:
N:1 -> S:hello
N:2 -> S:world
S:first -> N:1
S:second -> N:2
有注意到,前面的大写字母N表示number,S表示string类型,依次类推,取类型的第一个字母(大写)表示类型。
有注意到注释中:
--_G["print"] = function () end
如果把这句前面的注释去掉,则util.dump_table什么也不会输出,这样的好处就是控制了工程中所有的print,相当于一个开关,方便上线的时候直接屏蔽print,而开发时候,又可以打开print。