2015年4月2日 星期四

[Corona SDK] What is the difference between "else if" and "elseif"?

The basic usage of if is:
local i = 0
if(i==1) then
 print(1)  --> will not print
end
Note that there should have a then after if.
Actually, most languages also have similar syntax.
However, they can accept that we omit the then.
But for Lua, it is a must.

How about adding a else ?
local i = 0
if(i==1) then
 print(1)  --> will not print
else
 print(0)  --> will print
end

Nested if in 2 layers:
local i = 0
if(i==1) then
 print(1)  --> will not print
elseif (i==0) then
 print(0)  --> will print
else
 print(123) --> will not print
end

Can elseif be written as else if ?
local i = 0
if(i==1) then
 print(1)  --> will not print
else if (i==0) then
 print(0)  --> will print
else
 print(123) --> will not print
end
end
It seems that the results are the same, except for that one extra end is added.
Why?

Nested for more layers:
local i = 0
if(i==1) then
 print(1)  --> will not print
elseif (i==2) then
 print(2)  --> will not print
elseif (i==0) then
 print(0)--> will print
else
 print(123) --> will not print
end

Again, change elseif to be else if :
local i = 0
if(i==1) then
 print(1)  --> will not print
else if (i==2) then
 print(2)  --> will not print
else if (i==0) then
 print(0)--> will print  
else
 print(123) --> will not print
end
end
end
Well, 3 end are added?

It is because that for else, we will go into its body if previous conditions are all false.
For elseif, it means that we will need to check the condition after it to decide if we should go into its body.
For else if, it means that we have entered the body of else, then we add one condition if.

We can add two lines in the codes (line 5 and line 9) to make it clear:
local i = 0
if(i==1) then
 print(1)  --> will not print
else 
 print("enter 1") --> will print 
 if (i==2) then
 print(2)  --> will not print
else 
 print("enter 2") --> will print 
 if (i==0) then
 print(0)--> will print  
else
 print(123) --> will not print
end
end
end
If it is not clear enough, we can re-layout the codes without modify the content:
local i = 0
if(i==1) then
 print(1)  --> will not print
else 
 print("enter 1") --> will print 
 if (i==2) then
  print(2)  --> will not print
 else 
  print("enter 2") --> will print 
  if (i==0) then
   print(0)--> will print  
  else
   print(123) --> will not print
  end 
 end
end

So, the standard usage is:
if(condition 1) then
 --do some things
elseif (condition 2) then
 --do some things
 .
 .
elseif (condition n) then
 --do some things
else
 --do some things
end

沒有留言:

張貼留言