Lua Learning (--lua for Loop)

Source: Internet
Author: User
Tags lua

There are two broad classes of the For statement in the Lua programming language:: value for loop generic for loop value for loop

The value for loop syntax format in the Lua programming language:

For Var=exp1,exp2,exp3     
 do < actuators > End 
   

var changes from Exp1 to EXP2, each time it changes to exp3 increments of Var, and executes an "Executive Body". EXP3 is optional and, if not specified, defaults to 1. Instance

For I=10,1,-1 does
    print (i)
end

For three expressions are evaluated once before the start of the loop, and are no longer evaluated. For example, the above f (x) is executed only once before the start of the loop, and the result is used in a subsequent loop.

function f (x)  
    print ("function", x) return x*2 end for  
i=1,f (5) Does 
    print (i)  
end  

Output results:

function 5
1
2
3
4
5 6 7 8 9 10

You can see that the function f (x) executes only once before the loop starts. generic for Loop

A generic for loop traverses all values through an iterator function, similar to a foreach statement in Java.
Generic for-loop syntax format in LUA programming languages:

--Print all values of array a for  
i,v in Ipairs (a) does 
    print (v) End 
  

I is the array index value, and V is the array element value of the corresponding index. Ipairs is an iterator function provided by LUA to iterate over an algebraic group.

Instance
Loop array Days:

Days = {"Suanday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} for  
i,v into Ipairs (days)  
    do Print (v) End 
   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.