is async os.pullEvent() possible? #1237
-
this problem is the main reason i quit using computercraft out of frustration back in the day, how do i use os.pullEvent() without it stopping the execution of the rest of the script? as far as i can tell parallel is no help here because parallel doesn't work as advertised. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 9 replies
-
Due to how ComputerCraft works only a few computers can run at a time. This means that computers have to pause for others to run, Lua does this by yielding, which ComputerCraft wraps as event pulling. What are you doing that requires async event pulling? |
Beta Was this translation helpful? Give feedback.
-
This definitely sounds like a documention problem. Would you be able to provide some code you think should work but doesn't? |
Beta Was this translation helpful? Give feedback.
-
the function at line 496 is what i want to run in parallel with everything else. |
Beta Was this translation helpful? Give feedback.
-
i tried that in the while true loop at the bottom all it did was freeze the main code and only run chat monitoring |
Beta Was this translation helpful? Give feedback.
-
So you can do this one of two ways. I personally like the second method a bit better. Multi-event pullingBasically, you don't apply a filter to Examplewhile true do
local event_data = table.pack(os.pullEvent())
-- event name is stored as event_data[1]
if event_data[1] == "monitor_touch" then
-- act on the monitor touch
-- you can do the following if you wish to separate out the values returned by os.pullEvent as well:
local monitor_touched, x, y = table.unpack(event_data, 2, event_data.n)
elseif event_data[1] == "rednet_message" then
-- act on the rednet message
end
end Cons
ParallelYou can run multiple functions in "parallel." So if you have two functions with a Examplelocal function monitor_handler()
while true do
local _, monitor_touched, x, y = os.pullEvent("monitor_touch")
-- handle the touch event
end
end
local function rednet_handler()
while true do
local _, sender, message, protocol = os.pullEvent("rednet_message")
-- handle the rednet event
end
end
parallel.waitForAny(monitor_handler, rednet_handler) Pros
|
Beta Was this translation helpful? Give feedback.
So you can do this one of two ways. I personally like the second method a bit better.
Multi-event pulling
Basically, you don't apply a filter to
os.pullEvent()
, then use anif
statement on the event returned to separate what you want to do.Example