Search code examples
variablesprintingioluagarrys-mod

Lua Others can run my code perfectly fine but I run into errors?


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

Solution

  • 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.