-
my code probably looks bad but uh i cant get my coroutine running here's the code so uh when i like try to run these two loops together only the second one runs and im losing braincells why local caller = coroutine.create(function()
print("test")
while true do
print("caller")
local event, side, channel, replyChannel, message, distance
repeat
event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
until channel == ch
print(replyChannel)
if replyChannel == 15 then
local selected_floor = message
local current_floor = getCurrentFloor()
gotoFloor(selected_floor, current_floor)
end
end
end)
coroutine.resume(caller)
while true do
os.pullEvent("redstone")
local selected_floor
local current_floor
local is_selected
is_selected = getIsSelected()
if is_selected then
selected_floor = getSelectedFloor()
current_floor = getCurrentFloor()
if selected_floor ~= current_floor then
gotoFloor(selected_floor, current_floor)
end
end
end |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The main thing to note about coroutines, is that they're not "true" preemptive threads, like you might see in other languages. You can't actually have multiple coroutines at once - instead you switch between coroutines using This means when you call The trick here is to put both loops inside their own coroutines, and then have a loop which pulls events and feeds them into both coroutines. In your case, you can actually get away with using the parallel.waitForAll(function()
print("test")
while true do
print("caller")
local event, side, channel, replyChannel, message, distance
-- etc...
end
end, function()
while true do
os.pullEvent("redstone")
local selected_floor
local current_floor
-- etc...
end
end) |
Beta Was this translation helpful? Give feedback.
The main thing to note about coroutines, is that they're not "true" preemptive threads, like you might see in other languages. You can't actually have multiple coroutines at once - instead you switch between coroutines using
coroutine.resume
(which resumes a coroutine) orcoroutine.yield
(which stops running this coroutine and returns to whichever one rancoroutine.resume
).This means when you call
coroutine.resume(caller)
, you run your coroutine until the firstos.pullEvent("modem_message")
, but after that it's never run again - hence the loop no longer running!The trick here is to put both loops inside their own coroutines, and then have a loop which pulls events and feeds them into bo…