Main Content

Checking if the user has entered a number (Lua)

Archive - Originally posted on "The Horse's Mouth" - 2009-08-13 13:49:44 - Graham Ellis

In Lua, there's a difference between 0 and nil - and that means that you can easily code to ask your user to enter a number, testing the result and allowing him to enter zero as a legitimate value. That may sound like it's no big deal, but you don't want a loop to exit on a premature 0.

Here's code to ask for a numeric response:
io.write("Please enter the age of your dog: ")
stuff = tonumber (io.read())
if stuff then

and you can be assured that the chunk will run even if a zero was entered, but will not run if a non-numeric value is given. [full source code]

That extends very easily into a loop if you need to keep asking until you get a number:
while not stuff do
  io.write("Please enter the age of your dog: ")
  stuff = tonumber (io.read())
  if not stuff then print ("Duh!") end
end

with this code relying on the non-existent variable stuff returning a false at initial entry to the loop. [full source of example]