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

Error when entering string into toNumber()

Started by cheeselord99, 04 January 2014 - 08:33 AM
cheeselord99 #1
Posted 04 January 2014 - 09:33 AM
I'm writing some code for a basic message sending/receiving program in lua, which works, except for the fact that, if anything other than an integer is entered into the "ID" section of the send function, it returns "parallel:22: startup:9: attempt to call nil". Is there any way I can only allow numbers to go through into the function, or only allow numbers to be entered in at that point? My code is below, thanks :)/>

rednet.open("left")
function receive() -- this bit is fine
  id,message = rednet.receive()
  print(id..": "..message)
end
function send()
  read() -- waits for user to hit enter before asking for ID/Message
  write("Enter ID of Client: ")
  id = toNumber(read())
  write("Enter Message: ")
  message = read()
  rednet.send(id,message)
end
while true do
  parallel.waitForAny(receive,send) -- so both can run in parallel
end
Bubba #2
Posted 04 January 2014 - 01:56 PM
tonumber, not toNumber
Bomb Bloke #3
Posted 04 January 2014 - 05:50 PM
function send()
  read() -- waits for user to hit enter before asking for ID/Message

  local id
  while not id do  -- Variables count as false if undefined/nil.
    write("Enter ID of Client: ")
    id = tonumber(read())  -- tonumber() returns nil if it can't perform the conversion.
  end

  write("Enter Message: ")
  local message = read()

  rednet.send(id,message)
end