当前位置: 移动技术网 > IT编程>脚本编程>Lua > 使用lua实现php的print_r()函数功能

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

2017年12月08日  | 移动技术网IT编程  | 我要评论
之前写了一些类似php的函数,下面再来一个print_r()函数,代码如下: 复制代码 代码如下: function pr (t, name, indent) 

之前写了一些类似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) 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网