打印 Lua 的 table

最近有朋友告诉我 gist 访问不了,让我把一些代码贴到博客里。以后我就挑一些代码放到这里吧。


今天放的是打印 lua 中 table 结构的代码。代码参考了云风大哥的代码思路,但做了小的修改,一个是只支持字符串和数字作为 key,另外不处理自己包含自己的过程,这样代码更加简单,同时修改了输出格式,使得它更容易被人阅读。


gist:https://gist.github.com/rangercyh/5814003


function print_lua_table (lua_table, indent)
	indent = indent or 0
	for k, v in pairs(lua_table) do
		if type(k) == "string" then
			k = string.format("%q", k)
		end
		local szSuffix = ""
		if type(v) == "table" then
			szSuffix = "{"
		end
		local szPrefix = string.rep("    ", indent)
		formatting = szPrefix.."["..k.."]".." = "..szSuffix
		if type(v) == "table" then
			print(formatting)
			print_lua_table(v, indent + 1)
			print(szPrefix.."},")
		else
			local szValue = ""
			if type(v) == "string" then
				szValue = string.format("%q", v)
			else
				szValue = tostring(v)
			end
			print(formatting..szValue..",")
		end
	end
end


输出如下:

wKioL1QaLG3iVCQQAACFQMI_EWA964.jpg


你可能感兴趣的:(lua,table打印,lua打印table)