技术开发 频道

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

  【IT168 技术文档】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
相关文章