2014-10-17 24 views
-1

我正在研究一個項目,我想每隔5秒更新一次屏幕上的時鐘,除非用戶輸入內容。這是我到目前爲止的代碼,Computer Craft中的多線程功能

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") 

不幸的是,它不工作。如果有人能幫助我,我會很感激。謝謝:)

+0

什麼是「不工作」是什麼意思? – 2014-10-17 12:39:17

回答

0

你想要做這樣的事情(我不是在做正確的在屏幕上繪製,只有時間)

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 

此外,在適當的forum問這個,你有更多的機會得到一個回答那裏!另一個注意事項是,更多地進行事件處理,這確實有幫助。

0

僅供參考如果在同時執行多個例程時沒有「多線程」。它有什麼是'線程停車'。你可以在例程之間切換(yielding)並切換回來,它會在它停止的地方恢復,但是在任何給定的時間只有一個例程會被激活。

這是我去到Lua的參考,其中詳細解釋: http://lua-users.org/wiki/CoroutinesTutorial