lua实现php的print_r 函数功能

-- example usage:
--
-- require 'print_r'
-- a = {x=1, y=2, label={text='hans', color='blue'}, list={'a','b','c'}}
-- pr(a, 'My table')
--
--My table = {
--|  y = 2
--|  x = 1
--|  list = {
--|  |  [1] = "a"p
--|  |  [2] = "b"
--|  |  [3] = "c"
--|  }
--|  label = {
--|  |  color = "blue"
--|  |  text = "hans"
--|  }
--}
--
-- Copyright 2009: hans@hpelbers.org
-- This is freeware


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 emptyempty
          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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值