lua学习之table类型
关系表类型,这是一个很强大的类型。我们可以把这个类型看作是一个数组。只是
?
C
语言的数组,只能用正整数来作索引;?在
Lua
中,你可以用任意类型的值来作数组的索引,但这个值不能是
?nil
。同样,在
C
语言中,数组的内容只允许一种类型;在
?
Lua
中,你也可以用任意类型的值来作数组的内容,
nil也可以
。
基本介绍
注意三点:?
第一,所有元素之间,总是用逗号?","?隔开; 第二,所有索引值都需要用?"["和"]"?括起来;如果是字符串,还可以去掉引号和中括号;?即如果没有[]括起,则认为是字符串索引 第三,如果不写索引,则索引就会被认为是数字,并按顺序自动从?1往后编;
例如:
tt?
=?
{
"hello"?
,
33
}
value?
=?
4
tab?
=?
{[
tt
]?
=?
"table"
,
key?
=?
value
,?
[
"flag"?
]?
=?
nil
,?
11
}
print
(
tab
[
tt
])
print
(
tab.key
)
print
(
tab
[
1?
])
以上写法都是对的。
look = {[www] = "ok"}这样是不对的,www没有赋值,所以默认为nil因此出错table index is nil
---
temp = 1
tab = {[temp] = 1,11}
print(tab[temp]) --此时的结果是11,因为11没有显式对应的key,因此从1开始,如果前面定义了,则覆盖其value
temp = 2
tab = {[temp] = 1,11}
temp = 1
print(tab[temp]) -- 结果是11,虽然定义时[temp] = 1,但是后来我们改变了temp的值,所以指向另外的key了?
以上可知:
1.对于字符串,在{}定义时,可以
key = value,也可以["flag"] = nil,索引都是string类型,对于非nil类型
变量(包括字符串)
,都可以[variable]=value的方式
2.使用table时,对于字符串,可以通过.的方式访问,也可以通过[]方式访问。tab[a],tab[b],只要a==b那么tab[a]可以访问到tab[b]的值
3.不管定义索引时用的是常量还是变量,最终table中value的索引key是常量,不会随变量的改变而变化该value的key
嵌套
tb11=?{tb12?=?{bool?=?true}}?-- simple,it's a table IN a table :)
-- Call magic!
print
(
tb11.tb12.bool?
)?
-- works fine,since it's calling the key and value correctly.
print
(
tab11
[
"tb12"?
].
bool?
)?
--same as line 33
print
(
tab11.tb12?
[
"bool"
])?
--same as line 33
print
(
tab11
[
"tb12"?
][
"bool"
])?
--same as line 33
修改table的value
--Altering a table's content. Basically manipulating the values of the keys.
lucky
=?
{
john
=
"chips"?
,
jane?
=
"lemonade"
,
jolene
=
"egg salad"?
}
lucky.jolene?
=?
"fruit salad"?
--changed the value to "fruit salad" instead of "egg salad"
lucky.jerry?
=?
"fagaso food"?
-- adding a new key-value pair to the container lucky.
lucky.john?
=?
nil?
-- remove john from giving anything or from being a key.
table的易变性
a?=?{};?b?=?a;
print(a?==?b)??--> true
c,d?=?{},{};
print(c?==?d)?-->false
table库函数使用
-----------------------------------------------------------
Sorts table elements in a given order,?in-place,from? |