使用lua实现php的print_r()函数功能
之前写了一些类似php的函数,下面再来一个print_r()函数,代码如下:
functionpr(t,name,indent)
localtableList={}
functiontable_r(t,name,indent,full)
localid=notfullandnameortype(name)~="number"andtostring(name)or'['..name..']'
localtag=indent..id..'='
localout={} --result
iftype(t)=="table"then
iftableList[t]~=nilthen
table.insert(out,tag..'{}--'..tableList[t]..'(selfreference)')
else
tableList[t]=fulland(full..'.'..id)orid
ifnext(t)then--Tablenotempty
table.insert(out,tag..'{')
forkey,valueinpairs(t)do
table.insert(out,table_r(value,key,indent..'| ',tableList[t]))
end
table.insert(out,indent..'}')
elsetable.insert(out,tag..'{}')end
end
else
localval=type(t)~="number"andtype(t)~="boolean"and'"'..tostring(t)..'"'ortostring(t)
table.insert(out,tag..val)
end
returntable.concat(out,'\n')
end
returntable_r(t,nameor'Value',indentor'')
end
functionprint_r(t,name)
print(pr(t,name))
end
locala={x=1,y=2,label={text='hans',color='blue'},list={'a','b','c'}}
print_r(a)