Lua for loop
Lua programming language for loop can repeat the statement specified number of repetitions can be controlled for statement.
Lua programming language for the statement, there are two ::
- Value for loop
- Generic for loop
Value for loop
Lua programming language value for loop syntax:
for var=exp1,exp2,exp3 do <执行体> end
var changes from exp1 to exp2, as each change to exp3 increments of var, and perform a "executable." exp3 is optional, if not specified, the default is 1.
Examples
for i=1,f(x) do print(i) end for i=10,1,-1 do print(i) end
Three expressions for one-time evaluation before the start of the cycle, will no longer be evaluated. For example, the above f (x) only once before the start of the cycle, and the results used in a later cycle.
Verify the following:
#!/usr/local/bin/lua function f(x) print("function") return x*2 end for i=1,f(5) do print(i) end
The above example output is:
function 1 2 3 4 5 6 7 8 9 10
You can see the function f (x) is executed only once before the loop begins.
Generic for loop
For generic circulated through an iterator function to traverse all values, similar to java in the foreach statement.
Lua programming language generic for loop syntax:
--打印数组a的所有值 for i,v in ipairs(a) do print(v) end
i is the array index value, v is the corresponding index of the array element values. ipairs Lua is provided an iterator function for iterative array.
Examples
Loop arrays days:
#!/usr/local/bin/lua days = {"Suanday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"} for i,v in ipairs(days) do print(v) end
The above example output is:
Suanday Monday Tuesday Wednesday Thursday Friday Saturday