Lua Learning (3) -- Control Structure

Source: Internet
Author: User

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.

 

 

 

 

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.