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

[Question] How do I use read() to control a cobblegen

Started by Theray070696, 03 April 2012 - 01:29 PM
Theray070696 #1
Posted 03 April 2012 - 03:29 PM
I am trying to use the read() event to control how long my cobble generator will run for. This is for Feed the Beast. My code is here (don't know how to do spoilers)
print("Cobblestone Generator Control")
sleep(1)
print("How long should this run for?")
read(m)
redstone.setOutput( "right", true )
os.startTimer(m)
redstone.setOutput( "right", false )

The error I get is timer:6: bad argument: double expected, got nil

Is there any way to do this?
EatenAlive3 #2
Posted 03 April 2012 - 03:43 PM
A double is a number like 1.5, or 20, and the error is in line 6. When you are trying to assign the variable m to whatever the user types in, it's only being used a parameter for read(). To assign a variable, do m = read().

Read() will only give you a string, which isn't what os.startTimer() uses; to convert it to a number, do os.startTimer(tonumber(m)).
OniNoSeishin #3
Posted 03 April 2012 - 03:55 PM
also, os.startTimer(m) will throw an event after 'm' seconds, which you have to catch with os.pullEvent() inside a loop.
Something like this:

m = read()
yourTimer = os.startTimer(m) -- here you start the timer

while true do
  local event, argument = os.pullEvent()

  if (event == "timer") and (argument == yourTimer) then
    break -- exit from loop when timer ended
  end
end

OR, if you need something simplier, just use sleep(m), which pause the script for 'm' seconds
MrPiggles #4
Posted 03 April 2012 - 05:07 PM
For stuff like this, it's generally a good idea to use some error protection.

Here's an example of how I'd do it:

local m = read()
local yourTimer = os.startTimer(tonumber(m) or 0) -- If m can't be made into a number, it reverts to 0 instead
Theray070696 #5
Posted 03 April 2012 - 08:02 PM
also, os.startTimer(m) will throw an event after 'm' seconds, which you have to catch with os.pullEvent() inside a loop.
Something like this:

m = read()
yourTimer = os.startTimer(m) -- here you start the timer

while true do
  local event, argument = os.pullEvent()

  if (event == "timer") and (argument == yourTimer) then
	break -- exit from loop when timer ended
  end
end

OR, if you need something simplier, just use sleep(m), which pause the script for 'm' seconds
Thanks, this works perfectly!