Lua provides a set of traditional and small control structures, including if for conditional execution, while, repeat, and for iteration. All control structures have a realistic termination Symbol: If for while all end with end, repeat with until as the end.
Conditional expressions in the control structure can make any value. Lua treats all false and nil values as "true ".
1. if then else statement
if a<0 then a=0endif a<b then return aelse return bend
Nested if, elseif can be used
if op=="+" then r = a+b;elseif op=="-" then r = a-b;elseif op=="*" then r = a*b;elseif op=="/" then r = a/b;else error("invalid operation")end
2. While
i =1while i<10 do print(i) i=1+1;end
3. Repeat
The until condition is true.
repeat print(i)
i=i+1until i >10
4. Digital For Loop
Syntax
For exp1, exp2, exp3 DO <code> initial doexp1 value, exp2 termination value, exp3 is the step size. The default size of the Step exp3 is 1.
for i=1,10,2 do print(i)end
for i=1,10 do print(i)end
Similar to C and C ++, there are also break statements to terminate the use of math. Huge.
for i=1,math.huge do if i>5 then break end print(i)end
4. Generic For Loop
for i,v in ipairs(tb) doprint(v)end
The basic Lua Library provides ipairs, a function used for Array iteration. In each loop, I is assigned an index value, and V is assigned an array element value that should be indexed.