pullEvent isn't resumed when run in a coroutine #1774
-
Minecraft Version1.19.x Version1.101.4 DetailsDescriptionIf I could be misunderstanding something here, so I apologize if I am. My understanding is that calling I don't want to use the parallel API because its methods block - I need to run my code in a loop and I want to avoid blocking. local function CheckInput()
while true do
print("Waiting...")
local evt, key = os.pullEvent("key")
print(key)
end
end
local co = coroutine.create(CheckInput)
coroutine.resume(co) --Start
while true do
--local _, key = os.pullEvent("key")
--print("Works in main loop")
sleep(0)
end
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
So Lua doesn't really have any notion of coroutine scheduler. When you resume a coroutine, it runs that coroutine until it yields, and then restores control to the caller. This means resuming a coroutine is always going to be a "blocking" operation. Of course, that doesn't mean you can't write your own! Typically what one does is wrap the whole program in a coroutine dispatch loop, and then run the main body of the program a coroutine. Then when you need to run background code, you can add a coroutine to the dispatcher. There's a very simple example of this in this comment, but there's lots of alternative designs you can go for, like metis's Footnotes
|
Beta Was this translation helpful? Give feedback.
So Lua doesn't really have any notion of coroutine scheduler. When you resume a coroutine, it runs that coroutine until it yields, and then restores control to the caller. This means resuming a coroutine is always going to be a "blocking" operation.
Of course, that doesn't mean you can't write your own! Typically what one does is wrap the whole program in a coroutine dispatch loop, and then run the main body of the program a coroutine. Then when you need to run background code, you can add a coroutine to the dispatcher.
There's a very simple example of this in this comment, but there's lots of alternative designs you can go for, like metis's
await
module1.Footnotes
Not really recommend…