luaopencomputers

Is there a way to set a timeout for waiting for an event in Lua? (Opencomputer's lua)


I was creating a script which would send something and wait for it to be received back, but it just hang.

Here's my script:

local component = require("component")
local event = require("event")
local m = component.modem -- get primary modem component
m.open(80)
print(m.isOpen(80)) -- true

while true do


local timeout = 3
local timeoutEnded = false
function(
wait(timeout)
timeoutEnded = true
end)
local re = io.read()
m.broadcast(80, re)
while timeoutEnded == false do
local message = event.pull("modem_message")
end
if message == re then
print("sent success")
else
print("dammit")
end
end

when running, it would just hang up at waiting for "local message = event.pull("modem_message")" but since i was trying to get it to tell me if it transmitted successfully within 1 seconds and this was not my purpose i am clueless on how to make it timeout and continue executing (also i'm new to lua)


Solution

  • I know this is a bit late, but I thought I might add this (for anyone else who might need this too)


    As Luke100000 said, you can add a timeout to the ' event.pull() ' command.

    This is how that would look :

    event.pull(3,"modem_message")

    This will wait for the message for 3 seconds and if there is none it will simply continue with the program.

    What I would do, however, is run the ' event.listen() ' command which would not stop the program at all.

    For example :

    event.listen("modem_message",print)

    This will print out all the information from the message as soon as it is received, and the rest of the program can run separately from the listener until you turn it off by running ' event.ignore("modem_message",print) '

    Any function can be used in the place of print. The information is passed to the function from the event.

    Also remember that if you don't turn it off the listener will stay on even if you exit the program, until you reboot the computer!