SoFunction
Updated on 2025-03-10

Example of using Lua process control statement if else

Lua provides if statements and if else statements as process control statements. Of course, it conforms to the characteristics of C. Nested operations can be implemented between process statements, and of course process control can also be combined with the loop body for control.

1. If statement

if(Boolean expressions)
then
 --[ 在Boolean expressions为 true Statements executed when --]
end

Case:

i = 0 ;   --Define a variablei,and initialize0
if i < 5   --ifi Less than 5
then
 while(true) --At this time, do a loop1
 do
  i = i+1 ;
  print("i:",i);
  if i == 5  --ifi equal 5 
  then
  break ;  --Exit the loop
  end
 end
end

Explanation run:lua  

result:

i:      1
i:      2
i:      3
i:      4
i:      5

2. If else statement

if(Boolean expressions)
then
 --[ Boolean expressions为 true Execute the statement block when --]
else
 --[ Boolean expressions为 false Execute the statement block when --]
end

Case:

num = 3 ;
if num < 0
then 
 print("num is smaller than 0!");
else
 print("num is bigger than 0!");
end 

Explanation run:lua

result:

num is bigger than 0!

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below