打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
lua学习笔记 4 迭代法遍历 table,当Table中含Table时,递归输出

迭代法遍历 table,当Table中含Table时,递归调用。打印Table中 K, V值


通过type(arg) 判断当前类型


[plain] 
  1. table1 = {  
  2.     name = "Android Developer",  
  3.     email = "hpccns@gmail.com",  
  4.     url = "http://blog.csdn.net/hpccn",  
  5.     quote = [[  
  6.     There are   
  7.     10 types of pepole  
  8.     who can understand binary.  
  9.     ]],--多行文字  
  10.     embeddedTab = {  
  11.         em1 = xx,  
  12.         x =0,  
  13.         {x =1, y =2 } -- 再内嵌table  
  14.     }-- 内嵌table   
  15. }  
  16.   
  17. tab = "    "  
  18. function print_table(t, i)  
  19.     local indent ="" -- i缩进,当前调用缩进  
  20.     for j = 0, i do   
  21.         indent = indent .. tab  
  22.     end  
  23.     for k, v in pairs(t) do   
  24.         if (type(v) == "table") then -- type(v) 当前类型时否table 如果是,则需要递归,  
  25.             print(indent .. "< " .. k .. " is a table />")  
  26.             print_table(v, i + 1) -- 递归调用  
  27.             print(indent .. "/> end table ".. k .. "/>")  
  28.         else -- 否则直接输出当前值  
  29.                   
  30.             print(indent .. "<" .. k .. "=" .. v.."/>")  
  31.         end  
  32.     end  
  33. end  
  34.   
  35.   
  36. print_contents(table1, 0)  


输出结果:

for k,v in pairs(table) do 这样的遍历顺序并非是table中table的排列顺序,而是根据table中key的hash值排序来遍历的。

与Java中 HashMap, C++中的Map相似。

[plain] 
  1.    <name=Android Developer/>  
  2.    <quote=   There ar   
  3. 10 types of pepole  
  4. who can understand binary.  
  5. />  
  6.    <url=http://blog.csdn.net/hpccn/>  
  7.    < embeddedTab is a table />  
  8.        < 1 is a table />  
  9.            <y=2/>  
  10.            <x=1/>  
  11.        /> end table 1/>  
  12.        <x=0/>  
  13.    /> end table embeddedTab/>  
  14.    <email=hpccns@gmail.com/>  



学习重点: 

1 数据类型的判断: type()

lua语言中的数据类型主要有:nil、number、string、function、table、thread、boolean、userdata。

需要确定一个变量的类型时,可以使用内置函数type获取,如下:

[plain]
  1. type(“hello world”);              ---->string  
  2. type(type);                            ---->function  
  3. type(3.1415);                       ---->number  
  4. type(type(type));                  ---->string  



2 迭代法 

pairs 迭代全部的项

ipairs 迭代以数字做键值的项,且从1 开始

[plain] 
  1. for k, v in pairs(t) do   

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
lua 中pairs 和 ipairs区别(转)
cnblogs: Lua 中 ipairs 与 pairs 的区别 – perzy 小脚本之家 | 小脚本之家
Struts迭代器(iterator)遍历List常用的4种例子
田蕴章★【书法讲座】→100集
在 C++ 中遍历 Lua table
热更新(一)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服