table是lua语言中最为重要,也是最为强大的武器,最简单的构造函数是{}。--所以说当你看到{}的时候,实际上是调用了一个构造函数。
直接初始化数组:
days = {"Monday","Tuesday","Wednesday"}
初始化一个表作为record:
days = {m = "Monday",t = "Tuesday",w="Wednesday"}
//注意record其实相当于以m,t,w作为下表,所以默认的下表days[0]返回nil
添加域:可以向表中添加任何类型的域,构造函数{}仅影响初始化。
w = {x = 0,y = 0,label="console"} x = {sin(0),sin(1),sin(2)} w[1] = "another field" x.f = w
//域即键值
用table构造链表:
list = nil for line in io.lines() do list = {next = list,value = line} end l = list while 1 do print(l.value) l = l.next end
record和list混搭:
polyline = {color = "blue",thickness = 2,npoints = 4, {x = 0, y = 0}, {x = -10, y = 0}, {x = -10, y = 1}, {x= 0, y = 1} } print(polyline[1].x)
list和record风格是一般初始化的特例:
{x=0,y=0} <--> {["x"]=0,["y"]=0}
{"red","green","blue"} <--> {[1] = "red",[2] = "green",[3] = "blue"}
如果想要数组从0开始:(不建议)
days = {[0] = "Sunday","Monday","Tuesday","Wednesday"}
构造函数的,是可选的,方便以后扩展/ ,和;可以相互替代。