-1

I'm working on a project where I want to update the clock on screen say every 5 seconds unless the user inputs something. This is the code I have so far,

function thread1()
  term.clear()
  term.setCursorPos(1,1)
  write (" SteveCell        ")
  local time = os.time()
  local formatTime = textutils.formatTime(time, false)
  write (formatTime)
  print ("")
  print ("")
  for i=1,13 do
    write ("-")
  end
  print("")
  print ("1. Clock")
  print ("2. Calender")
  print ("3. Memo")
  print ("4. Shutdown")
  for i=1,13 do
    write ("-")
  end
  print ("")
  print ("")
  write ("Choose an option: ")
  local choice = io.read()
  local choiceValid = false
  if (choice == "1") then
    -- do this
  elseif (choice == "2") then
    -- do that
  elseif (choice == "3") then
    -- do this
  elseif (choice == "4") then
    shell.run("shutdown")
  else
    print ("Choice Invalid")
    os.sleep(2)
    shell.run("mainMenu")
  end
end

function thread2()
  localmyTimer = os.startTimer(5)
  while true do
    local event,timerID = os.pullEvent("timer")
    if timerID == myTimer then break end
  end
  return
end

parallel.waitForAny(thread1, thread2)
shell.run("mainMenu")

Unfortunately it's not working. If someone could help me with this, I would really appreciate it. Thanks :)

emufossum13
  • 377
  • 1
  • 10
  • 21

2 Answers2

0

You want to do something like this (Im not doing the correct on screen drawing, only the time)

local function thread1_2()
   -- both threads in one!

   while true do
      local ID_MAIN = os.startTimer(5)
      local ID = os.startTimer(0.05)
      local e = { os.pullEvent() }
      if e[1] == "char" then
         -- Check all the options with variable e[2] here
         print( string.format( "Pressed %s", e[2] ) )
         break -- Getting out of the 'thread'
      elseif e[1] == "timer" and e[2] == ID then
         ID = os.startTimer(0.05) -- shortest interval in cc
         redrawTime() -- Redraw and update the time in this function!!!
      elseif e[1] == "timer" and e[2] == MAIN_ID then
         break
      end
   end
end

Also, ask this in the proper forum, you have more chance getting an answer there! Another note, get more into event handling, it really helps.

engineercoding
  • 832
  • 6
  • 14
0

FYI Lua doesn't have 'multi-threading' as in executing multiple routines simultaneously. What it does have is 'thread parking.' You can switch between routines (yielding) and switch back and it will resume where it left off, but only a single routine will be active at any given time.

This is my go-to Lua reference, which explains in detail: http://lua-users.org/wiki/CoroutinesTutorial

Ashlyn Black
  • 101
  • 2