18

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.

1
  • As for your crashing issues, I'm going to assume it just closes straight away? To fix this, you want to open the Lua interpreter and enter dofile("your_file.lua"). This will run it in interactive mode, and stop it from closing after the error is shown. (You could also add "pause" to the end of your build script)
    – Deco
    Commented Jan 24, 2012 at 17:14

1 Answer 1

35

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.

2
  • I sorry,i forgot to mention that the variable myvalue is a text,so to get the exact numbers stored on the text i must use the quotes!UPDATED THE VALUES.
    – Mateus
    Commented Jan 24, 2012 at 6:40
  • 1
    @MateusNunes: You should probably convert your text (known as a "string") to a number. See my edit.
    – voithos
    Commented Jan 24, 2012 at 6:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.