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

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

2.table的下标
例e05.lua
-- Arrays
myData = {}
myData[0] = “foo”
myData[1] = 42

-- Hash tables
myData[“bar”] = “baz”

-- Iterate through the
-- structure
for key, value in myData do  
print(key .. “=“ .. value)
end

输出结果
0=foo
1=42
bar=baz

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

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

Lua对Table占用内存的处理是自动的, 如下面这段代码
  a = {}
  a["x"] = 10
  b = a     -- `b' refers to the same table as `a'
  print(b["x"]) --> 10
  b["x"] = 20
  print(a["x"]) --> 20
  a = nil   -- now only `b' still refers to the table
  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
-- Table ‘constructor’
myPolygon = {  
color=“blue”,  
thickness=2,  
npoints=4;  
{x=0,   y=0},  
{x=-10, y=0},  
{x=-5, y=4},  
{x=0,   y=4}
}

-- Print the color
print(myPolygon[“color”])

-- Print it again using dot
-- notation
print(myPolygon.color)

-- The points are accessible
-- in myPolygon[1] to myPolygon[4]

-- Print the second point’s x
-- coordinate
print(myPolygon[2].x)

程序说明
首先建立一个table, 与上一例不同的是,在table的constructor里面有{x=0,y=0},
这是什么意思呢? 这其实就是一个小table, 定义在了大table之内, 小table的
table名省略了.
最后一行myPolygon[2].x,就是大table里面小table的访问方式.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值