Gunnar Erikson
Gunnar Erikson

Reputation: 27

LUA from if statement to loop with if elseif statements

function checkCurrency(checker)
  return (checker % 2 == 0)
end

local currency1 = 105
local currency2 = 110
local currency3 = 115


if(checkCurrency(currency1) == true) then
      print("yes1")
elseif(checkCurrency(currency2) == true) then
      print("yes2")
elseif(checkCurrency(currency3) == true) then
      print("yes3")
else
      print("no currency available")
end

My idea of the code is to loop through 100 currencies but instead of writing currency1, currency2 etc I would like the same exact code in a few lines with something like a mathematical formula, because as you can see, the currency goes up 5 each time, so theres a start which is 105 and the end should be 500. And if none of them matches, it should throw an else statement in the end.

My initial idea was this:

function checkCurrency(checker)
  return (checker % 2 == 0)
end

for i = 105,500,5 
do 
   if(i == 105) then 
       if(checkCurrency(i) == true) then
          print("yes" .. i)
   end
   if(i ~= 105 and i ~= 500) then 
       elseif(checkCurrency(i) == true) then
          print("yes" .. i)
   end
   if(i == 500) then
      print("no currency available")
   end

end

But its not possible because it tries to end the second if statement instead of the first, so I have no idea how to solve this in a safe way, any tips or examples would be a nice start. Also I dont want to check every line, if it works on example currency5, it should stop, just as the first code with the if,elseif and end statements. So it dont loop through 500 currencies and waste resource invain.

Upvotes: 1

Views: 1728

Answers (2)

Aaron
Aaron

Reputation: 24802

You have multiple syntax errors :

  • you need to end your nested if (line 8's if is ended by line 10's end, while looking at tabulation you expect it to end the outer if)
  • you can't use elseif if you haven't a previous if at the same level (line 12)

A generic solution could look like that :

local valid
for i=105,500,5
do
    if(checkCurrency(i)) then
        valid=i
        break
    end
end
if (not valid) then 
    print("no currency available")
else
    print("Found " .. valid)
end

Upvotes: 3

luther
luther

Reputation: 5544

Use the loop to just find the matching currency. Store that currency in a variable. Use break to exit the loop. Then use an if--else to do your business with that currency.

local function checkCurrency(checker)
  return checker % 2 == 0
end

local currency
for i = 105, 499, 5 do
  if checkCurrency(i) then
    currency = i
    break
  end
end

if currency then
  print('yes' .. currency)
else
  print("no currency available")
end

Upvotes: 2

Related Questions