Lua table 简单理解

来源:互联网 发布:元数据驱动架构 编辑:程序博客网 时间:2024/04/28 22:22
1、 table 是 lua 中最重要的数据类型。 
2、 table 类似于 python 中的字典。 
3、 table 只能通过构造式来创建 

例1: 
Lua代码  收藏代码
  1. mytable = { a = 10, b = 11, c = 20, ddd = 30 }  
  2. print(mytable["a"])  



注释: 
1)、 table 中的每项要求是 key = value 的形式 
2)、 key 只能是字符串, 这里的 a, b, c, ddd 都是字符串,但是不能加上引号 
3)、 通过 key 来访问 table 的值,这时候, a 必须加上引号 

例2: 

Lua代码  收藏代码
  1. mytable = { 10, ddd = 301213 }  
  2.   
  3. print(mytable[1])  
  4. print(mytable[2])  
  5. print(mytable[3])  


注释: 
1)、 table 中可以出现没有 key 的项,这个时候,lua 会把这个 table 当做一个数组来看待,这个项的key就是它在数组中的下标(从1开始) 
2)、 上例中, mytable[1] 是 10, mytable[2] 是 12, ddd = 30 这项会被跳过。mytable[3] 是 13 


综上,可以发现, table 是一个数组和字典的混合体。
0 0
原创粉丝点击