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

 更新时间:2014年11月03日 16:04:34   投稿:hebedich  
笔者比较熟悉php,所以一直在做一些使用lua来实现php中函数的功能,算是自己对lua理解的一个小测试吧

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

相关文章

  • Lua中rawset和rawget的作用浅析

    Lua中rawset和rawget的作用浅析

    这篇文章主要介绍了Lua中rawset和rawget的作用浅析,本文分别用两段代码演示了rawset和rawget的作用,需要的朋友可以参考下
    2015-04-04
  • Lua中table的遍历详解

    Lua中table的遍历详解

    这篇文章主要介绍了Lua中table的遍历详解,本文讲解了4种遍历方法,并详细分析了这4种方法的特点、使用环境、相关知识等,需要的朋友可以参考下
    2015-04-04
  • C语言中调用Lua函数实例

    C语言中调用Lua函数实例

    这篇文章主要介绍了C语言中调用Lua函数实例,本文讲解了调用一个Lua函数的步骤和C语言调用Lua函数实例,需要的朋友可以参考下
    2015-04-04
  • Lua中数字for循环实例

    Lua中数字for循环实例

    这篇文章主要介绍了Lua中数字for循环实例,本文直接给出数字循环代码示例,并探讨了改变控制变量的一些问题,需要的朋友可以参考下
    2015-04-04
  • 深入探究Lua中的解析表达式

    深入探究Lua中的解析表达式

    这篇文章主要介绍了深入探究Lua中的解析表达式,对于其语法部分的说明和示例都超详细,极力推荐此文!需要的朋友可以参考下
    2015-07-07
  • Lua模块和模块载入浅析

    Lua模块和模块载入浅析

    这篇文章主要介绍了Lua模块和模块载入浅析,Lua模块其实就是以.lua结尾的文件,模块载入可以用requeire或者dofile,需要的朋友可以参考下
    2014-09-09
  • Lua中的函数写法简明示例

    Lua中的函数写法简明示例

    这篇文章主要介绍了Lua中的函数写法简明示例,本文是一篇个人学习笔记,简单的记录了Lua函数的写法,需要的朋友可以参考下
    2015-04-04
  • Lua基础迭代器的使用实例

    Lua基础迭代器的使用实例

    今天小编就为大家分享一篇关于Lua基础迭代器的使用实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • lua脚本语言快速入门教程

    lua脚本语言快速入门教程

    这篇文章主要介绍了lua脚本语言快速入门教程,本文讲解了变量及常量、字符串、逻辑控制语句、循环结构、函数及其使用等内容,需要的朋友可以参考下
    2015-03-03
  • lua操作excel方法分享

    lua操作excel方法分享

    这篇文章主要介绍了lua操作excel方法分享,在网上几乎没有找到像样的示例资料,所以自己写了份,推荐给大家。
    2015-03-03

最新评论