Lua: run code while waiting for input

1.6k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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)
2
On

Running multiple tasks is a very broad problem solved by the operating system, not something as simple as Lua interpreter. It is solved on a level much deeper than io.read and deals with troubles numerous enough to fill a couple of books. For lua vm instead of physical computer, it may be simpler but it would still need delving deep into how the letters of code are turned into operations performed by the computer.

That mod of yours seems to already emulate os functionality for you: 1,2. I believe you'll be better off by making use of the provided functionality.