Lua获取表中字段的名称

假设有下面这段代码

 
 
  1. local t =
  2. {
  3. a = 1,
  4. b = { x = 1, y = 2}
  5. }

我传给你一个table, 想要知道这个table都有哪些字段,但是又不能直接获取,这时可以使用下面这个方法

 
 
  1. for k, v in pairs (t) do
  2. print(tostring(k), v)
  3. end

292032219257004.png

可以看到, 把k用tostring函数转成字段串形式就OK了

但是我们还可以看到,当table中嵌套table的时候,嵌套的table无法打印出来,对于这种情况,难道就没有办法了吗?
当然不是,对于这种常见需求,肯定已经有人实现过了,这里先给出云风大神的print_r版本

 
 
  1. 树形打印一个table
  2. @param:root table的根节点
  3. function Utils.print_r(root)
  4. local cache = { [root] = "." }
  5. local function _dump(t,space,name)
  6. local temp = {}
  7. for k,v in pairs(t) do
  8. local key = tostring(k)
  9. if cache[v] then
  10. table.insert(temp,"+" .. key .. " {" .. cache[v].."}")
  11. elseif type(v) == "table" then
  12. local new_key = name .. "." .. key
  13. cache[v] = new_key
  14. table.insert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. string.rep(" ",#key),new_key))
  15. else
  16. table.insert(temp,"+" .. key .. " [" .. tostring(v).."]")
  17. end
  18. end
  19. return table.concat(temp,"\n"..space)
  20. end
  21. print(_dump(root, "" , ""))
  22. end

292032224878133.png
可以看到, 嵌套的table b中的x,y字段也已经打印出来了,但是这个版本是树形打印的, 如果对于比较复杂的表结构,打印起来特别难看,这时候可以看一下这个版本的

 
 
  1. function Utils.print_lua_table (lua_table, indent)
  2. indent = indent or 0
  3. for k, v in pairs(lua_table) do
  4. if type(k) == "string" then
  5. k = string.format("%q", k)
  6. end
  7. local szSuffix = ""
  8. if type(v) == "table" then
  9. szSuffix = "{"
  10. end
  11. local szPrefix = string.rep(" ", indent)
  12. formatting = szPrefix.."["..k.."]".." = "..szSuffix
  13. if type(v) == "table" then
  14. print(formatting)
  15. print_lua_table(v, indent + 1)
  16. print(szPrefix.."},")
  17. else
  18. local szValue = ""
  19. if type(v) == "string" then
  20. szValue = string.format("%q", v)
  21. else
  22. szValue = tostring(v)
  23. end
  24. print(formatting..szValue..",")
  25. end
  26. end
  27. end

原作地址:https://gist.github.com/rangercyh/5814003

但是这个不支持Key为Value的, 所以功能比较鸡肋,使用的时候还请小心!





转载于:https://www.cnblogs.com/chenhaobright/p/de867e794ca4c4bb82108899132aa6a2.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值