Forums » Suggestions

Request for a lua wait or sleep function

Aug 07, 2020 PaKettle link
Is there a wait or sleep function anywhere?
If not could you be so kind as to implement one?

I really hate having to add busy loops and timers tend to turn the code into spaghetti.....
Aug 08, 2020 incarnate link
So, obviously, Lua doesn't include this itself, and there are various solutions online using sockets, but that seemed pretty hacky, and I thought there might be a more appropriate design choice here.. where basically the answer is something like "use coroutines".

I pinged Ray about it, and he basically agreed, saying:

There's no sleep function outside of a coroutine.
They should use a coroutine to do that, or set up a timer that performs the action at a later time.
So instead of:
do thing 1
wait 1 second
do thing 2

Try:
do thing 1
local t = Timer()
t:SetTimeout(1000, function() do thing 2 end)

Or:
Thread.Create(function(threadid)
do thing 1
Thread.WaitForAnyTrigger(threadid, 1000)
do thing 2
end)
Aug 09, 2020 PaKettle link
Yeah I did see the online hacks and was equally unimpressed.
The co-routine version looks like a complicated busy loop and the timer approach turns bad when the function goes beyond a few lines.

Too much to hope for so I guess I am serving meatballs tonight :P
Thanks
Aug 09, 2020 incarnate link
I suspect the coroutine may be able to yield instead of being busy, but I'm not familiar with lua underlying architecture or scheduling. Anyway, sure.. did what I could.
Aug 10, 2020 Xeha link
Threads and timers are your friend to create a state machine, especially threads. If you do work on the main lua thread, the whole game "halts/lags" till you are done. Sleeps are a hacky workaround to acting to events.
Aug 10, 2020 PaKettle link
I know but I'm just a simple minded old geezer... Gotta keep things simple for old farts like me...