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

Problem with simple timer program

Started by DaCraftMiner, 06 June 2013 - 11:09 AM
DaCraftMiner #1
Posted 06 June 2013 - 01:09 PM
The goal of this program was to have a timer that starts/stops on a redstone current being on/off.


x = 0
input = redstone.getInput(left)
do
if input==true then print(..x+1)
sleep(1)
loop

I code mainly in Batch and Visual Basic, so some of the calls (mainly to use input== or input= in the if statement) I am not sure about.
Lyqyd #2
Posted 06 June 2013 - 08:11 PM
Split into new topic.
Bomb Bloke #3
Posted 06 June 2013 - 08:50 PM
Instead of do…loop, or while…wend, or if…endif, or for…next, Lua just uses "end" as a general loop-breaker. Note that "do" on its own won't loop here (though it can be used to declare some local variables and discard them quickly, something you won't want to do often); use a "while true do" statement for a quick'n'dirty infinite loop. Also note that "if" statements, even single line ones, MUST be "end"ed in Lua.

Eg:

while something do
  if something then
    for i=1,10 do
      somecode
    end
  end
end

When comparing things, use "==" to see if they're the same (instead of just "="), "~=" to see if they're different (instead of "<>"). When assigning values just use "=".

"input = redstone.getInput(left)" sets "input" to the state of the redstone signal when this line is called. "input" will either be "true" or "false", and it will not change when the redstone signal does; you'd need to call "redstone.getInput(left)" again to get an up-to-date status.

"input == true" will resolve as either true or false directly depending on whether "input" is true or false. You can hence simply specify "if input then".

To increment "x" you must use good ol' "x=x+1".

So with all that said, a quick re-write might look like this:

local x = 0        -- Pre-declare a couple of variables.
local event = ""   -- Somewhat less system-intensive then re-declaring them over and over later.

while true do    -- Repeat this loop forevah
  while redstone.getInput(left) do  -- Repeat this loop so long as we're getting a redstone signal.
    if x == 0 then print("Timer started!") end
    x=x+1
    print(x)
    sleep(1)
  end

  print("Timer stopped!")
  x=0
  event = os.pullEvent("redstone")   -- Causes the program to sleep until the redstone signal changes.
end

os.pullEvent() offers a number of ways to have your program sleep until a certain event occurs (and to get information about those events when they do).
DaCraftMiner #4
Posted 09 June 2013 - 06:55 PM
Thank you very much.