2014-03-19 37 views
1

我目前正在使用Lua进行一个简单的“猜数字”游戏。我正在通过iPad上的应用程序进行编程,名为TouchLua +。其中一种游戏模式是你有一定的时间来猜测数字。我认为要这样做,我会创建一个从给定时间开始倒计时的协程。出于某种原因,我不能在协程运行时输入数字。谁能帮忙?这是我到目前为止。Lua Coroutine错误

target = math.random(1, 100) 
    coroutine.resume(coroutine.create(function() 
    for i = 1, roundTime do 
     sleep(1000) 
     sys.alert("tock") 
    end 
    lose = true 
    coroutine.yield() 
    end)) 
    repeat 
    local n = tonumber(io.read()) 
    if (n > target) then 
     print("Try a lower number.\n") 
    elseif (n < target) then 
     print("Try a higher number.\n") 
    else 
     win = true 
    end 
    until (lose or win) 
    return true 

回答

2

协程并不是一种多处理的形式,它们是一种协作式多线程的形式。因此,在协程正在运行时,没有其他任何运行。协程意味着经常将控制权交还给调用者,并且调用者意图恢复协程,以使协程可以继续其产生的地方。您可以看到这将如何显示为并行处理。

所以你的情况,你会想从内环路产生,一个小的睡眠时间后:

co = coroutine.create(function() 
    for i = 1, roundTime do 
     sleep(1) 
     sys.alert("tock") 
     coroutine.yield() 
    end 
    lose = true 
end) 

不幸的是,你不能中断io.read(),这意味着以上的没用。理想情况下,你会希望有一个“io.peek”功能,这样你就可以做到以下几点:

while coroutine.status(co) ~= "dead" do 
    coroutine.resume(co) 
    if io.peek() then -- non-blocking, just checks if a key has been pressed 
     ... get the answer and process ... 
    end 
end 

我不知道在Lua非阻塞IO键盘的。假设TouchLua +支持C扩展,您可以创建一个向Lua公开部分C non-blocking keyboard input的C扩展。我怀疑它,因为它是一个iOS应用程序。

它似乎并没有出现时间循环或回调等,也找不到文档。如果您可以选择创建一个用户可以输入答案的文本框,并且他们必须点击接受,那么您可以测量所花费的时间。如果有时间循环,您可以在那里查看时间,并在时间不足的情况下显示消息。所有这些在科罗娜都很容易做到,也许在TouchLua +中是不可能的。