1 表
表通过构造器来创建和初始化。最简单的构造函数是{}。举个栗子:
table = {[1] = 0, "sunday", "monday", 0.3e12, 2,lable = "console", ["x"] = 5, x = 10, [0] = 15, [1] = 20,
[1] = "tuesday", [2] = 25, [7] = 30, {math.sin(0), math.sin(1)}, nil, false,[8] = 40, [9] = 50}
print("****************************")
print(#table)
print(table[0])
print(table[1])
print(table[2])
print(table[3])
print(table[4])
print(table[5])
print(table[6])
print(table[7])
print(table[8])
print(table[9])
print(table["x"])
print(table.x)
print("****************************")
for i,v in ipairs(table) do print(i,v) end
print("****************************")
table2 = { [1] = 20, [3] = 25}
print(table2[1])
print(table2[2])
print(table2[3])
print("****************************")
贴出运行结果:
****************************
9
15
sunday
monday
300000000000
2
table: 003BC948
nil
false
40
50
10
10
****************************
1 sunday
2 monday
3 300000000000
4 2
5 table: 003BC948
****************************
20
nil
25
****************************
从上面的代码和运行结果,我们可以得到一些结论:
1) lua中的表的元素的种类是可以混合的,同一个表中的元素的种类不要求一致。
2) lua中的表是可以嵌套的
3) x = 5 <==> ["x"] = 5,这两个是等价的,如果在同一个表中出现,后者是会覆盖前者。==>["x"] = 5, x = 10 && print(table["x"]) print(table.x) && 10 10
4) 列表式的元素定义的优先级貌似比【int】式的元素定义的优先级高。两种定义同时出现在一个表中,而且有冲突的情况下,列表式的优先级比【int】的优先级高, 【int】式定义的元素貌似被抛弃了。
2 if /while/repeat ... until/for
三种if:
1) if conditions then
then-part
end;
2) if conditions then
then-part
else
else-part
end;
3) if conditions then
then-part
elseif conditions then
elseif-part
--->多个elseif
else
else-part
end;
while:
while condition do
statements;
end;
repeat...until:
repeat
statements;
until conditions;
for:
1) for var=exp1,exp2,exp3 do
loop-part
end
for 将用exp3 作为step 从exp1(初始值)到exp2(终止值),执行loop-part。其中exp3 可以省略,默认step=1
有几点需要注意:
a. 三个表达式只会被计算一次,并且是在循环开始前。
b.控制变量var 是局部变量自动被声明,并且只在循环内有效。如果需要保留控制变量的值,需要在循环中将其保存。
c.3. 循环过程中不要改变控制变量的值,那样做的结果是不可预知的。如果要退出循环,使用break 语句。
2) 范型for:
范型 for 遍历迭代子函数返回的每一个值。
a. 控制变量是局部变量
b. 不要修改控制变量的值
3 参数与返回值
Lua 函数可以返回多个结果值,这个是我接触到的第一个可以返回多个返回值的编程语言,mark一下。