Lua学习(五)----表

来源:互联网 发布:ppt软件下载 编辑:程序博客网 时间:2024/04/28 13:52

--表
2--可以使用构造器来初始化表,表是Lua特有的功能强大的东西。最简单的构造函数是{},用来创建一个空表。
3local days = {"xiao""ta""hello""lua"}
4--第一个元素索引为1,以后的类推,这一点和其他语言的第一个元素索引是0不同,要特别注意,小心掉到坑里边。
5print(days[4])       --> lua
6 
7--构造函数可以使用任何表达式初始化
8local num = {1,2,3,4,5}
9--其实num的初始化等价于如下
10local num = {[1]=1,[2]=2,[3]=3,[4]=4,[5]=5}
11--访问元素的时候使用中括号
12print(num[1]) -->1
13 
14--还可以在初始化表的时候为元素提供一个索引
15local tab = {a=1,b=2}
16--等价于如下的初始化
17local tab = {["a"]=1,["b"]=2}
18print(tab["a"]) -->1
19--当索引值是字符串的时候可以使用tab.a的形式来访问元素,其实代表的就是tab["a"],要务必理解这种用法,当你访问表中元素出错的时候不妨看看是不是这个知识点没有掌握好,本人在这里就遇到了坑,所以只有多实践才能深刻体会。
20print(tab.a) -->1
21--注意区分tab["a"]和tab[a]这俩种形式,第一种代表的索引是字符串a,可以使用等价的形式tab.a来访问它的值
22--第二种代表的是使用a这个变量的值作为索引来访问
23local a = "haha"
24local tab2 = {a="hello",[a]="lua"}
25print(tab2.a) -->hello
26print(tab2[a]) -->lua
27 
28--向表中添加元素
29tab2.x = 3
30tab2[5] = 4
31--删除元素
32tab2.a = nil
33 
34--一个表中可以混合各种类型的值,可以是boolean,字符串,表,函数,等等
35local tab3 = {color="blue",{x=0,   y=0},thickness=2, npoints=false,
36              {x=-10, y=0},
37              {x=-30, y=1},
38              {x=0,   y=1}
39}
40--没有添加索引的时候索引默认从1开始
41print(tab3[2].x)     --> -10
42 
43--在构造函数的最后的","是可选的,可以方便以后的扩展
44local a = {[1]="red", [2]="green", [3]="blue",}
45--在构造函数中域分隔符逗号(",")可以用分号(";")替代,通常我们使用分号用来分割不同类型的表元素
46local tab4 = {x=10, y=45; "one""two""three"}

-- Simple empty table

mytable = {}
print("Type of mytable is ",type(mytable))

mytable[1]= "Lua"
mytable["wow"] = "Tutorial"
print("mytable Element at index 1 is ", mytable[1])
print("mytable Element at index wow is ", mytable["wow"])
--------------------
animal={"dog","cat","duck"}
print("contact string",table.concat(animal,", "))
---------------------
fruits = {"banana","orange","apple"}
-- insert a fruit at the end
table.insert(fruits,"mango")
print("Fruit at index 4 is ",fruits[4])

--insert fruit at index 2
table.insert(fruits,2,"grapes")
print("Fruit at index 2 is ",fruits[2])

print("The maximum elements in table is",table.maxn(fruits))

print("The last element is",fruits[5])
table.remove(fruits)
print("The previous last element is",fruits[5])
----------------------------------------
fruits = {"banana","orange","apple","grapes"}
for k,v in ipairs(fruits) do
print(k,v)
end
table.sort(fruits)
print("sorted table")
for k,v in ipairs(fruits) do
print(k,v)
end

--------------------
animal={"dog","cat","duck"}

print("contact string",table.concat(animal,", "))

在对表操作内置函数和它们被列于下表中。

S.N.方法及用途1table.concat (table [, sep [, i [, j]]]):
串连根据给定的参数表中的字符串。见范例细节。2table.insert (table, [pos,] value):
插入的值到表中的指定位置。3table.maxn (table)
返回最大的数字索引。4table.remove (table [, pos])
该值从表中删除。5table.sort (table [, comp])
排序基于可选的比较参数表。
0 0
原创粉丝点击