1

I'm currently working on a simple 'guess the number' game using Lua. I'm programming through an app on my iPad called TouchLua+. One of the game modes is you have a certain amount of time to guess the number. I thought that to do this, I would create a coroutine that counts down from the given time. For some reason, I can't input a number while the coroutine is running. Can anyone help? Here is what I have so far.

  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
user3314993
  • 287
  • 1
  • 4
  • 11

1 Answers1

2

Coroutines are not a form of multiprocessing, they are a form of cooperative multithreading. As such, while the coroutine is running, nothing else is running. A coroutine is meant to yield control back to the caller often, and the caller is meant to resume the coroutine so the coroutine can continue where it yielded. You can see how this will appear to be parallel processing.

So in your case you would want to yield from inside the loop, after a small sleep time:

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

Unfortunately, you can't interrupt io.read(), which means the above is of no use. Ideally you would want a "io.peek" function so you could do the following:

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

I am not aware of a non-blocking keyboard IO in Lua. You could create a C extension that exposes some of C non-blocking keyboard input to Lua, assuming that TouchLua+ supports C extensions. I doubt it, given that it is an iOS app.

It doesn't appear that there is a time loop or callbacks or such, and couldn't find docs. If you have option of creating a text box where user can enter answer and they have to click accept then you can measure how long it took. If there is a time loop you could check time there and show message if run out of time. All this is very easy to do in Corona, maybe not possible in TouchLua+.

Community
  • 1
  • 1
Oliver
  • 27,510
  • 9
  • 72
  • 103