使用lua实现php的print_r()函数功能

时间:2021-05-22

之前写了一些类似php的函数,下面再来一个print_r()函数,代码如下:

复制代码 代码如下:
function pr (t, name, indent)
local tableList = {}
function table_r (t, name, indent, full)
local id = not full and name or type(name)~="number" and tostring(name) or '['..name..']'
local tag = indent .. id .. ' = '
local out = {} -- result
if type(t) == "table" then
if tableList[t] ~= nil then
table.insert(out, tag .. '{} -- ' .. tableList[t] .. ' (self reference)')
else
tableList[t]= full and (full .. '.' .. id) or id
if next(t) then -- Table not empty
table.insert(out, tag .. '{')
for key,value in pairs(t) do
table.insert(out,table_r(value,key,indent .. '| ',tableList[t]))
end
table.insert(out,indent .. '}')
else table.insert(out,tag .. '{}') end
end
else
local val = type(t)~="number" and type(t)~="boolean" and '"'..tostring(t)..'"' or tostring(t)
table.insert(out, tag .. val)
end
return table.concat(out, '\n')
end
return table_r(t,name or 'Value',indent or '')
end
function print_r (t, name)
print(pr(t,name))
end

local a = {x=1, y=2, label={text='hans', color='blue'}, list={'a','b','c'}}

print_r(a)

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章