This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Copilot's profile picture

io.read() not working

Started by Copilot, 20 June 2013 - 10:24 PM
Copilot #1
Posted 21 June 2013 - 12:24 AM
So in my program I'm using the command io.read(). I want it to read numbers, so from my research I found out that in order to do that I need to type in io.read("*number"), but whenever I use that command it spits out "Unsupported format". What's the solution to this? How the heck do I get a user to enter a number?
Lyqyd #2
Posted 21 June 2013 - 12:55 AM
Split into new topic.

Don't use io.read(). Use plain ol' read() instead, and don't pass it any arguments. You can use tonumber() to convert the resulting string into a number. If the string cannot be converted into a number, tonumber() will return nil.
TheOddByte #3
Posted 21 June 2013 - 08:22 AM
Example of what Lyqyd said

input = read()

if not tonumber(input) then
print("False")

else
print("True")
end
theoriginalbit #4
Posted 21 June 2013 - 08:33 AM
And a way to keep trying until you get a number

write("enter a number: ")
local input = read()
while not tonumber(input) do
  print("not a number")
  write("enter a number: ")
  input = read()
end
the above will keep asking for a number until they enter one, telling them when they don't


local input
repeat
  write("enter a number: ")
  input = read()
until tonumber(input)
the above will just keep asking until they enter a number, this method you cannot tell them they entered incorrectly
Copilot #5
Posted 22 June 2013 - 12:54 AM
Woo! Thanks all!
johnnic #6
Posted 23 June 2013 - 12:13 AM
io.read() can only print what was written. read() can be used as read(var number or "string").
theoriginalbit #7
Posted 23 June 2013 - 03:47 AM
io.read() can only print what was written. read() can be used as read(var number or "string").
Not quite, io.read() does take input from the user, and will return the string of the input, just like read. the standard read can only return a string.