通过例子学习Lua(3)—Lua数据结构

开发 前端
Lua语言只有一种基本数据结构, 那就是table, 所有其他数据结构如数组啦、类, 都可以由table实现.

1.简介

Lua语言只有一种基本数据结构, 那就是table, 所有其他数据结构如数组啦、类, 都可以由table实现.

2.table的下标

例e05.lua

  1. -- Arrays 
  2. myData = {} 
  3. myData[0] = “foo” 
  4. myData[1] = 42 
  5. -- Hash tables 
  6. myData[“bar”] = “baz” 
  7. -- Iterate through the 
  8. -- structure 
  9. for key, value in myData do 
  10. print(key .. “=“ .. value) end 

输出结果

0=foo

1=42

bar=baz

程序说明

首先定义了一个table myData={}, 然后用数字作为下标赋了两个值给它. 这种定义方法类似于C中的数组, 但与数组不同的是, 每个数组元素不需要为相同类型,就像本例中一个为整型, 一个为字符串.

程序第二部分, 以字符串做为下标, 又向table内增加了一个元素. 这种table非常像STL里面的map. table下标可以为Lua所支持的任意基本类型, 除了nil值以外.

Lua对Table占用内存的处理是自动的, 如下面这段代码

  1. a = {} 
  2. a["x"] = 10 
  3. b = a -- `b' refers to the same table as `a' 
  4. print(b["x"]) --> 10 
  5. b["x"] = 20 
  6. print(a["x"]) --> 20 
  7. a = nil -- now only `b' still refers to the table 
  8.  
  9. b = nil -- now there are no references left to the table 

b和a都指向相同的table, 只占用一块内存, 当执行到a = nil时, b仍然指向table,

而当执行到b=nil时, 因为没有指向table的变量了, 所以Lua会自动释放table所占内存

3.Table的嵌套

Table的使用还可以嵌套,如下例

例e06.lua

  1. -- Table ‘constructor’ 
  2. myPolygon = { 
  3. color=“blue”, 
  4. thickness=2
  5. npoints=4
  6. {x=0y=0}, 
  7. {x=-10, y=0}, 
  8. {x=-5, y=4}, 
  9. {x=0y=4
  10. -- Print the color 
  11. print(myPolygon[“color”]) 
  12. -- Print it again using dot 
  13. -- notation 
  14. print(myPolygon.color) 
  15. -- The points are accessible 
  16. -- in myPolygon[1] to myPolygon[4] 
  17. -- Print the second point’s x 
  18. -- coordinate 
  19. print(myPolygon[2].x) 

程序说明

首先建立一个table, 与上一例不同的是,在table的constructor里面有{x=0,y=0},这是什么意思呢? 这其实就是一个小table, 定义在了大table之内, 小table的table名省略了。

最后一行myPolygon[2].x,就是大table里面小table的访问方式。

原文链接:http://tech.it168.com/j/2008-02-14/200802141314299.shtml

责任编辑:陈四芳 来源: 来自ITPUB论坛
相关推荐

2013-12-13 15:48:52

Lua脚本语言

2013-12-13 16:46:18

Lua脚本语言

2013-12-12 17:30:03

Lua例子

2013-12-13 16:53:00

Lua脚本语言C++

2013-12-13 15:54:32

Lua脚本语言

2011-08-23 16:59:16

C++LUA脚本LUA API

2021-01-12 06:42:50

Lua脚本语言编程语言

2011-08-23 11:13:56

Lua

2011-08-23 13:27:46

Luaglobal变量

2011-08-23 15:34:56

Lua模式 匹配

2011-08-24 11:03:33

LUA环境 安装

2011-08-24 14:14:13

LUA环境 配置

2011-08-23 16:37:05

Lua数学库

2011-08-31 15:59:10

LUAWeb 开发

2011-08-23 17:33:08

LuaMetatable

2011-08-24 15:22:09

2011-08-24 15:42:38

LUA源代码

2011-08-25 15:41:42

Lua源码

2011-08-23 10:29:13

LuaPlayer

2011-08-24 15:34:44

MinGWLua环境配置
点赞
收藏

51CTO技术栈公众号