lua基础之lua表结构

lua基础之lua表结构:

http://www.lua.org/pil/2.5.html

1.在lua中,nil不是0,也不是空字符串"",索引值从1开始。

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" refers to the table
b = nil --now there are no references left to the table
--此时lua内存管理将删除表并重新利用它的内存。

2.表中可以存储不同类型的索引,可以动态增长其存储长度。

a = {}  --empty table
--create 1000 new entries
for  i = 1, 1000 do a[i] = i*2 end
print(a[9])   -->18
a["x"] = 10
print(a["x"])  -->10
print(a["y"])  --> nil 未初始化的值为nil,并且如果需要删除一个全局变量,直接给其赋值nil即可。

3.除了索引之外,也可以使用a.name指代a[“name”]。

a.x = 10  ---same as a["x"] = 10
print(a.x)  --same as print(a["x"])
print(a.y)  --same as print(a["y"])

初学者容易混淆a.x和a[x]

a = {}
x = "y"
a[x] = 10    -- put 10 in field "y"
print(a[x])  ---> 10 -- value of  field "y"
print(a.x)   ---> nil --value of field "x"
print(a.y)   --->10  --value of field "y"

有点绕!a.name的时候记得name是字符串“name”。

4.数字索引

-- read 10 lines storing them in a table
for i = 1,10 do 
	a[i] = io.read()
end
-- 打印
--the array ends with its first nil element
for i, line  in ipairs(a) do 
	print(line)
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值