16

I can't seem to get this to work. I come from Python, so I tried using the same syntax for the hell of it, but it unsurprisingly wouldn't work:

var = 4

for var in range(2,20) do
print ("var is in range")
      end
azonicrider
  • 189
  • 1
  • 1
  • 5

2 Answers2

31

If you want to test whether a value is in a range, use

if var>=2 and var<=20 then
   print ("var is in range")
end

If you want a loop, use

for var=2,20 do
   print(var)
end
lhf
  • 70,581
  • 9
  • 108
  • 149
  • 1
    Python ranges exclude the `stop` value, so the equivalent Lua loop would have been `for var = 2, 19 do ... end`. – Luatic Aug 15 '22 at 08:10
3

You could write your range function easily enough:

function range ( from , to )
    return function (_,last)
            if last >= to then return nil
            else return last+1
            end
        end , nil , from-1
end
daurnimator
  • 4,091
  • 18
  • 34
  • That'd would be a for generator but the OP seems to want a condition tester. – lhf Aug 21 '12 at 10:04
  • 1
    I don't think so; see http://docs.python.org/tutorial/controlflow.html#the-range-function . Obviously using a numeric for loop is the correct solution; but he can still have his generator if he wants ;) – daurnimator Aug 21 '12 at 14:13