2015年4月1日 星期三

[Corona SDK] Expressions

Arithmatic Operators
Most basic arithmetic operations are supported: +(addition), -(subtraction), *(multiplication), /(division), %(modulo), ^(exponentiation)
Take a look at the example directly:
print(17+2)      --> 19
print(-17-2)     --> -19
print(17*5)      --> 85
print(17/3)      --> 5.6666666666667
print(17%5)      --> 2
print(17^2)      --> 289
print(17^(-0.5)) --> 0.24253562503633, equal to square root

Relational Operators
There have few types:
==     ~=      <      <=      >       >=
== is used to check if two variables or objects are the same or not.
It will check their types first. If their types are different, it will return false directly.
If their types are the same, then it will compare their values.
That is, the string and number conversion mentioned in [Corona SDK] Basic types are not applied here.
For example, 123 == "123" will return false.

For table and function, the comparison is done by reference, not by value.
As example shown below, the result will be false, even these two tables have the same contents.
t1 = {my,"123"}
t2 = {my,"123"}
print(t1==t2)   --> false
~= is the negation of ==.

Logical Operators
or: Return the first argument if it is not false and not nil. Otherwise, it will return the second argument.
and: Return the first argument if it is false or nil. Otherwise, it will return the second argument.
not: Return true or false, no matter what the original type is.
print(1 or 2)            --> 1
print(nil or true)       --> true
print(false or nil)      --> nil
print(3 and 4)           --> 4
print(not nil)           --> true
print(nil and "test")    --> nil
print(false and nil)     --> false
print(1 or 2 and 3)      --> 1
print(nil or 2 and 3)    --> 3
print(nil and 2 or 3)    --> 3

Concatenation
Use ".." to concatenate two strings.
The string and number conversion mentioned in [Corona SDK] Basic types are applied here.
print("a" .. "b")       --> ab
print("a" .. 2)         --> a2
print(1 .. 2)           --> 12

Length Operator
Add # in front of string or table variable can get the length information.
a = "hello"
print(#a)       --> 5
c = {}
c[1] = "33"
c["a"] = "55"
c[2] = "33"
print(#c)       --> 2
d = {}
d[0] = "33"
d["a"] = "55"
d[1] = "33"
d[3] = "33"
print(#d)       --> 1
e = {}
e[2] = "33"
e["a"] = "55"
e[3] = "33"
print(#e)       --> 0
For table type, the length will be the last number index in continuous sequence.
If the value of index 1 is nil, the length will be 0. 
For example,  c[1],c[2] have continuous index and c[1] is not nil. The length is the last index 2.
For d[0],d[1],d[3], the index sequence is not continuous. The length will be the last index in continuous sequence, which is 1. 
For e[2],e[3], the index sequence is continuous. However, e[1] is nil. The length will be 0.

沒有留言:

張貼留言