A:
1、算数运算符:加+
,减-
,乘*
,除/
,负-
,乘方^
。
2、关系运算符:小于<
、大于>
、小于等于<=
、大于等于>=
、等于==
、不等于~=
。
3、逻辑运算符:并且and
,或or
,非not
。
4、字符串连接符..
。
A:C语言中的&&
和||
中所有表达式都可以作为判断条件,并且最终返回的值一定是true
或者false
。而Lua中and
和or
只将第一个表达式作为判断条件,并且最终返回的是其中一个条件的值。
遵循如下规则:
and
的第一个条件如果为假,则返回第一个条件的值;否则返回第二个条件的值。
or
的第一个条件如果为真,则返回第一个条件的值;否则返回第二个条件的值。
print(4 and 5) --> 5
print(nil and 13) --> nil
print(false and 13) --> false
print(4 or 5) --> 4
print(false or 5) --> 5
A:优先级从高到低:
^
not - (unary)
* /
+ -
..
< > <= >= ~= ==
and
or
^
和..
这两个二元操作符是右结合,其他的二元操作符都是左结合。
对优先级以及结合性混乱的话,还是最好是用()
吧。
A:
a, b = 10, 2*x -- 相当于"a = 10; b = 2*x;"
Lua在同时对多个变量赋值时,首先计算值,然后再赋给变量。可以利用这一特性实现两个变量值的交换:
x, y = y, x -- swap 'x' for 'y'
a[i], a[j] = a[j], a[i] -- swap 'a[i]' for 'a[j]'
在同时对多个变量赋值时,Lua可自动调整每个变量所获得的值。当给出的值少于给出的变量时,额外的变量会被赋值为nil
;而当给出的值多于给出的变量时,额外的值会被忽略:
a, b, c = 0, 1
print(a,b,c) --> 0 1 nil
a, b = a+1, b+1, b+2 -- value of b+2 is ignored
print(a,b) --> 1 2
a, b, c = 0
print(a,b,c) --> 0 nil nil
A:使用local
关键字。
--[[ 此例在Lua的“stand-alone interpreter”模式中测试会不正常,
因为第二行本身是一个"chunk",接下来第三行会被认定为一个新的"chunk",那时"i"已经不存在了。]]
-- 如果想在Lua的“stand-alone interpreter”模式中测试此例,请将代码写在"do-end"中。
-- do
x = 10
local i = 1 -- local to the chunk
while i<=x do
local x = i*2 -- local to the while body
print(x) --> 2, 4, 6, 8, ...
i = i + 1
end
if i > 20 then
local x -- local to the "then" body
x = 20
print(x + 2)
else
print(x) --> 10 (the global one)
end
print(x) --> 10 (the global one)
-- end
A:
-- if
if cond then
dosomething
end
if cond then
dosomething
else
dosomething
end
if cond then
dosomething
elseif cond then
dosomething
... -- elseif
else
dosomething
end
-- while
while cond do
dosomething
end
–- repeat
repeat
dosomething
untile cond
-- do
do
dosomething
end
-- Numeric for
for var = beginval, endval, valstep do -- valstep如果不写,默认是1。
dosomething
end
-- Generic for
for var1, var2, ... in exp do
dosomething
end
-- break,可以写在任何循环中。
break
-- return,可以写在任何函数中。
return ret1, ret2, ..., or nothing
1、lua认定tables, userdata, functions是否相等,是通过他们的引用,而非他们的值。这就好像C语言中比较两个指针是否相等一样。
a = {}; a.x = 1; a.y = 0
b = {}; b.x = 1; b.y = 0
c = a
print(a == c) --> true
print(a == b) --> false
2、lua比较字符串通过从每个字符串的第一个子符开始,按顺序比较两个字符串中对应位置的子符,只要其中一个字符的ASCII值比另一个大,则整个字符串就大于另一个字符串,否则个字符串小于另一个字符串。
3、只有数字与数字之间,字符串与字符串之间可以比较大小。其他相同种类或不同种类的值之间只能比较是否相等。
4、需要注意的是,Lua中只认定false
和nil
为假,其他的值均为真。所以,
print(not 0) --> false
5、两个关于and
和or
有用的使用方式,
x = x or v -- x如果没有被赋值,则默认值为v。
(a and b) or c -- 当b为true时,相当于"a ? b : c"。
6、Lua中局部变量的访问速度比全局变量快,所以可以使用局部变量时请尽可能使用。
7、”Numeric for”中”beginval”, “endval”, “valstep”如果给的是表达式,只会在for开始时计算一次,在for运行过程中不会再被计算。
-- f(x)只会在开始时计算一次,for中如果改变了x的值,f(x)也不会再被计算。
for i=1,f(x) do
print(i)
end
8、break
和return
只能写在”chunks”的结尾,如果写在中间会报错。如果你一定要写在中间,请将其用do-end
包起来。