3
votes

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
As far as I understamd coroutines they are functions that can be paused with yield() and continued at a later point. What I need is something that runs while the main loop is running to. Something like a second thread like in C#.BDevGW
There may be an os.Event that you can listen for to see if input is availableratchet freak
As a matter of fact, there is. Also, @BDevGW, threads are of rather limited use in opencomputers, and I wouldn't suggest you use them if you are new to opencomputers... You should use event handling (or timers) and coroutines instead.Promitheas Nikou

2 Answers

1
votes

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.

1
votes

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)