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

来源:互联网 发布:java写入word文件 编辑:程序博客网 时间:2024/06/05 00:25

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


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


  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] view plaincopy
  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] view plaincopy
  1. type(“hello world”);              ---->string  
  2. type(type);                            ---->function  
  3. type(3.1415);                       ---->number  
  4. type(type(type));                  ---->string  



2 迭代法 

pairs 迭代全部的项

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

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


0 0
原创粉丝点击