Arithmetic operator
The arithmetic operators in Lua are:
"+" (addition):
Copy Code code as follows:
"-" (subtraction):
Copy Code code as follows:
"*" (multiplication):
Copy Code code as follows:
"/" (division):
Copy Code code as follows:
"^" (index):
Copy Code code as follows:
"%" (modulo):
Copy Code code as follows:
Relational operators
Lua provides the following relational operators:
Copy Code code as follows:
The result of the operation returned by the above operator is either true or false. Strings and numbers cannot be compared
logical operators
Logical operators have and, or, not
Copy Code code as follows:
Print (1 and 2)
Print (nil and 1)
Print (FALSE and 2)
Print (1 or 2)
Print (False or 5)
The logical operator treats false and nil as false, others as true.
Local Variables and scopes
Lua creates local variables by means of a local statement whose scope is limited to the block that declares them.
Copy Code code as follows:
Local A, B = 1, 10
If a < b then
Print (a)
Local A
Print (a)
End
Print (A, B)
Saving global variables with local variables can speed up access to global variables in the current scope. For the effect of acceleration, compare the following calculations for the execution time of the Fibonacci sequence (Fibonacci):
Copy Code code as follows:
function Fibonacci (N)
If n < 2 Then
return n
End
Return Fibonacci (N-2) + Fibonacci (n-1)
End
Io.write (Fibonacci), "\ n")
Use local variables
Copy Code code as follows:
Local function Fibonacci (n)
If n < 2 Then
return n
End
Return Fibonacci (N-2) + Fibonacci (n-1)
End
Io.write (Fibonacci), "\ n")
Control structure
If then ElseIf else end
Copy Code code as follows:
if num = = 1 Then
Print (1)
ElseIf num = = 2 Then
Print (2)
Else
Print ("other")
End
Lua does not support switch statements
While
First judge the while condition, if the condition is true, follow the execution loop body, or end
Copy Code code as follows:
Local i = 1
While A[i] do
Print (A[i])
i = i + 1
End
Repeat-until
Execute the loop body first, then judge the condition, if the condition is true, exit the loop body, otherwise continue to execute the loop body. Do-while statements similar to other languages, the loop body will execute at least once
Copy Code code as follows:
Local A = 1
Repeat
A = a + 1
b = A
Print (b)
Until B < 10
For loop
There are two forms of a For Loop statement: Numeric for (numeric for), generic for (generic for)
Numeric for syntax:
Copy Code code as follows:
For start and end
Doing something
End
Start is the starting value, end is the ending value, and step is stride (optional, default is 1)
Copy Code code as follows:
For a = ten, 0,-2 do
Print (a)
End
The generic for loop traverses all values through an iterator (iterator) function:
Copy Code code as follows:
tab = {Key1 = "val1", Key2 = "Val2", "Val3"}
For K, V in Pairs (tab) do
if k = = "Key2" Then
Break
End
Print (K.. " - " .. V
End
Break and return statements are used to jump out of the currently executing block.