Search code examples
luaminecraftopencomputers

Lua: run code while waiting for input


I'm currently working on a lua program. I want to use it in Minecraft with a mod called "OpenComputers" which allows the use of lua scripts on emulated systems. The programm I'm working on is relatively simple: you have a console and you enter a command to control a machine. It looks like this:

while(true) do
  io.write("Enter command\n>")
  cmd = io.read()
  -- running code to process the command
end

But the problem is: I need a routine running in the background which checks data given by the machine.

while(true) do
  -- checking and reacting
end

How can I make this work?

  • I can't jump to a coroutine while waiting on io.read()
  • It's not enough to check after someone used a command (sometimes I don't use it for days but I still have to keep an eye on it)

I'm relatively new to lua so please try to give a simple solution and - if possible - one that does not rely on third party tools.

Thank you :)


Solution

  • If you have some experience with opencomputers, you can add a(n asynchronous) listener for "key_down", and store the user input in a string (or whatever you want).

    For example:

    local userstr = ""
    function keyPressed(event_name, player_uuid, ascii)
        local c = string.char(ascii)
        if c=='\n' then
            print(userstr)
            userstr = ""
        else
            userstr=userstr..c
        end
        --stores keys typed by user and prints them as a string when you press enter
    end
    
    event.register("key_down", keyPressed)