现在的位置: 首页Lua>正文
lua实现php的print_r()函数功能 [原创]
2012年01月29日 Lua 评论数 3 ⁄ 被围观 20,969 次+

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

  1. function pr (t, name, indent)   
  2.     local tableList = {}   
  3.     function table_r (t, name, indent, full)   
  4.         local id = not full and name or type(name)~="number" and tostring(name) or '['..name..']'   
  5.         local tag = indent .. id .. ' = '   
  6.         local out = {}  -- result   
  7.         if type(t) == "table" then   
  8.             if tableList[t] ~= nil then   
  9.                 table.insert(out, tag .. '{} -- ' .. tableList[t] .. ' (self reference)')   
  10.             else  
  11.                 tableList[t]= full and (full .. '.' .. idor id  
  12.                 if next(t) then -- Table not empty   
  13.                     table.insert(out, tag .. '{')   
  14.                     for key,value in pairs(t) do   
  15.                         table.insert(out,table_r(value,key,indent .. '|  ',tableList[t]))   
  16.                     end   
  17.                     table.insert(out,indent .. '}')   
  18.                 else table.insert(out,tag .. '{}') end   
  19.             end   
  20.         else  
  21.             local val = type(t)~="number" and type(t)~="boolean" and '"'..tostring(t)..'"' or tostring(t)   
  22.             table.insert(out, tag .. val)   
  23.         end   
  24.         return table.concat(out, '\n')   
  25.     end   
  26.     return table_r(t,name or 'Value',indent or '')   
  27. end   
  28. function print_r (t, name)   
  29.     print(pr(t,name))   
  30. end   
  31.   
  32. local a = {x=1, y=2, label={text='hans', color='blue'}, list={'a','b','c'}}   
  33.   
  34. print_r(a)  

本文地址:http://www.92csz.com/22/1036.html
如非注明则为本站原创文章,欢迎转载。转载请注明转载自:moon's blog
 

目前有 3 条留言 其中:访客:1 条, 博主:1 条 引用: 1

  1. 朱定聪的博客 : 2012年01月31日02:30:33  -49楼

    😆 博主你好,贵博友链已做好哦~~

    • clairelume : 2012年01月31日10:32:18

      友链已加首页 😛