Suppose there is the following code:
local t =
{
a = 1,
b = { x = 1, y = 2}
}
I will pass you a table and want to know which fields are in this table, but cannot be obtained directly. In this case, you can use the following method:
for k, v in pairs (t) do
print(tostring(k), v)
end
We can see that it is okay to convert K into a field string using the tostring function.
However, we can also see that when a table is nested in a table, the nested table cannot be printed out. In this case, is there no way to do this?
Of course not. Someone has already implemented this common requirement. Here we will first provide the print_r version of Yunfeng.
Print a table in a tree shape,
@ Param: Root Node of the root table
function Utils.print_r(root)
local cache = { [root] = "." }
local function _dump(t,space,name)
local temp = {}
for k,v in pairs(t) do
local key = tostring(k)
if cache[v] then
table.insert(temp,"+" .. key .. " {" .. cache[v].."}")
elseif type(v) == "table" then
local new_key = name .. "." .. key
cache[v] = new_key
table.insert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. string.rep(" ",#key),new_key))
else
table.insert(temp,"+" .. key .. " [" .. tostring(v).."]")
end
end
return table.concat(temp,"\n"..space)
end
print(_dump(root, "" , ""))
end
As you can see, the X and Y fields in the nested table B have been printed, but this version is tree-like. If it is difficult to print complex table structures, at this time, you can take a look at the version
function Utils.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
Original: https://gist.github.com/rangercyh/5814003
However, this does not support key-value, so the function is quite tasteless. Please be careful when using it!
From Weizhi note (wiz)
Lua obtains the field name in the table.