Lua学习(二)表达式

1、算数操作符:+ - * / ^ %
^ 指数运算
x^2    --->x的平方
x^0.5  --->x的评分根

% 取模(求余)运算,定义如下:
a%b = a - math.floor(a/b)*b

x%1       -->x的小数部分
x-x%1     -->x的整数部分
x-x%0.01  -->x精确到小数点后两位


2、关系操作符 < > <= >= == ~=
  对于table,userdata和函数,lua是作引用比较,只有当引用同一个对象时,才相等
a = {x=1,y=2}
b = {x=1,y=2}
c = a
结果:a==c 但 a~=b


3、逻辑操作符 and or not :false和nil为假,其它都为真
and和or都是短路求值,只会才有需要的时候,才去评估第二个值
and : 第一个参数为假时,取第一个参数
print(4 and 5)    --->5
print(5 and 4)    --->4

or : 第一个参数为真时,取第一个参数
print(false or 4)   --->4
print(4 or 5)       --->4
print(5 or 4)       --->5


4、字符串连接 ..
print("hello" .. "world")  --->"hello world"
print(0..1)   --->01


5、table构造式 {}
  1、数组构造
colors = {"red", "orange", "yellow", "green", "cyan", "blue", "purple"}
print(colors[1]) ---->red


  2、记录构造
a = {x=10, y=40}
print(a["x])    --->10
print(a.x)      --->10


  3、记录风格和列表风格混合
mix = {color="yello", name="jj", {x=1,y=2},{x=3,y=4}}
print(mix["color"])    --->yello
print(mix.name)        --->jj
print(mix[1].x)        --->1
print(mix[2]["x"])     --->3


  4、显式构造
ob = {["name"]="jj", ["number"]=10}

猜你喜欢

转载自room-bb.iteye.com/blog/2294099