Lua for cycle


Release date:2023-09-27 Update date:2023-10-13 Editor:admin View counts:297

Label:

Lua for cycle

In Lua programming language the for loop statement can repeat the specified statement, and the number of times can be repeated in the for control in the statement.

In Lua programming language for , there are two main categories of statements:

  • Numerical value for cycle

  • Generics for cycle

Numerical for cycle

Lua numerical value in programming language for circular syntax format:

for var=exp1,exp2,exp3 do
    <executor>
end

var from exp1 change to exp2 , with each change to exp3 increase step by step var and execute the “executive body” once. exp3 is optional, if not specified, defaults to 1.

Example

Example

for i=1,f(x) do
    print(i)
end

for i=10,1,-1 do
    print(i)
end

for are evaluated once before the start of the loop, and will not be evaluated later like the one above. f(x) is executed only once before the loop starts, and the result is used in later loops.

Verify as follows:

Example

#!/usr/local/bin/lua
function f(x)
    print("function")
    return x*2
end
for i=1,f(5) do print(i)
end

The output result of the above example is:

function
1
2
3
4
5
6
7
8
9
10

You can see the function. f(x) execute only once before the loop starts.

Generic for loop

Generics for loop iterates through all values through an iterator function, similar to the one in java foreach statement.

Lua generics in programming languages for circular syntax format:

--Print all values of array a
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end

i is an array index value v is the array element value of the corresponding index. ipairs is an iterator function provided by Lua to iterate through arrays.

Example

Cyclic array days :

Example

#!/usr/local/bin/lua
days =
{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}

for i,v in ipairs(days) do  print(v) end

The output result of the above example is:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Powered by TorCMS (https://github.com/bukun/TorCMS).