Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - if statement with two conditions on the same variable?

How can I set a lower and upper bound value for a variable in a if-statement in lua programming language? I need something like the pseudocode below.

if ("100000" >= my_variable <= "80000") then
     do stuff...
end

I've tried different formats but my application keeps crashing.

Update:

To anyone with the same sort of doubts about lua's syntax, i'd recommend checking the documentation here and keeping it handy. It'll be useful while learning.

like image 816
Mateus Avatar asked Jan 24 '12 06:01

Mateus


People also ask

Can you put an if statement inside an if statement Lua?

It is always legal in Lua programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).

What does Elseif mean in Lua?

Adding an elseif — then statement to an if — then structure lets you check if alternative conditions are true, assuming the preceding conditions are false. Lua will go from top to bottom, stop at the first true condition it encounters, and execute its block of code.

What does ~= mean in Lua?

The ~= symbol or operator in Lua is known as the not-equal to operator. In many programming languages you might have seen the symbol !=


1 Answers

You should convert your string to a number, if you know for sure that it should be a number, and if there is no reason for it to be a string.

Here's how to do a comparison for a range:

myVariable = tonumber(myVariable)

if (100000 >= myVariable and myVariable >= 80000) then
    display.remove(myImage)
end

Notice the and. Most programming languages don't expand the form x < y < z to x < y AND y < z automatically, so you must use the logical and explicitly. This is because one side is evaluated before the other side, so in left-to-right order it ends up going from x < y < z to true < z which is an error, whereas in the explicit method, it goes from x < y AND y < z to true AND y < z to true AND true, to true.

like image 189
voithos Avatar answered Oct 22 '22 21:10

voithos