加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 22:28:59 所属栏目:大数据 来源:网络整理
导读:1.简介 Lua语言只有一种基本数据结构,那就是table,所有其他数据结构如数组啦,类啦,都可以由table实现. 2.table的下标 例e05.lua -- Arrays myData = {} myData[0] = “foo” myData[1] = 42 -- Hash tables myData[“bar”] = “baz” -- Iterate through th
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,这是什么意思呢? 这其实就是一个小table,定义在了大table之内,小table的 table名省略了. 最后一行myPolygon[2].x,就是大table里面小table的访问方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读