0

I have a Lua script that I have been trying to get to work. It is my first Lua script. I asked someone else to run my code, and it worked perfectly fine for them. However, when I try to run it ANYWHERE (I have tried running in Ideone.com, codepad.com, lExecutor, Garry's Mod etc), I get the same error message. The error message is 'Attempt to compare nil with number' and it's on line 4. If it helps, my OS is windows 7. My code is below and I ask that you guys test it to see if it works. If possible, also state what you used to run it if it worked. Basically what it's meant to do is an input box will come up and the user has to input their age. If the age is over or under 12, it will say you are too old/young and if the age is 12 it will say 'Welcome, son!'.

io.write ("Enter your age:")
age = io.read()
age = tonumber(age)
if age < 12 then
  print ("O noes, you are too young!")
elseif age > 12 then
  print ("O noes, you are too old!")
else
  print ("Welcome, son!")
end
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
katooosha
  • 35
  • 1
  • 1
  • 7
  • `Attempt to compare nil with number` means that on that line your variable is `nil` and not a number. That will happen when the value read isn't convertible to a number. So if you enter `foo` at the prompt for example. If you enter a number it should work. – Etan Reisner Jul 08 '15 at 01:26
  • 1
    "when I try to run it ANYWHERE" The first place you should have tried is the [standard Lua interpreter](http://luabinaries.sourceforge.net/download.html) at the command line. – Mud Jul 08 '15 at 03:35

2 Answers2

2

io.read() reads from standard input, so it would work if you ran your script on the command line. That's all it does, it can't open input boxes. In the kind of environments you're trying to run your code, there is no standard input so age never gets assigned to anything and you get an error.

pvg
  • 2,673
  • 4
  • 17
  • 31
2

The code itself is fine. The problem is, if you try it out on websites like Ideone, you have to provide the input explicitly, otherwise age gets no input, so its value is nil, causing the error.

Demo on Ideone, note the stdin part.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294