r/lua • u/Uncle_Tree_ • Oct 15 '26
How to make a code delay in lua?
Hey im new to coding and wanted to learn lua ive got a few things down know and wanted to just write a little countdown nothing complicated just a first test but ran into the problem that i cant get a code delay to work
4
Upvotes
5
u/ICON_4 Oct 15 '26 edited Oct 15 '26
So there is no native sleep function in lua that you could use to "pause" your main thread, you can however use os.execute("sleep " .. x), should work with Unix or you could use a library.
If you’re ok with busy wait (meaning your lua process will still be executed/not send to sleep on OS level) you could assign a timestamp at the start of the delay to a variable and check if current time >= timestamp + x in a while loop, but this consumes cpu cycles (busy wait).
Are you using plain lua?
4
u/RelatableRedditer Oct 15 '26
It depends on where you're using Lua, because on its own it's quite concise. WarCraft 3 for example exposes its own native TimerStart which allows a precise enough delayed execution, and you can use coroutines to suspend a thread in the mean time if you wanted to have a thread sleep for a more sane method than busy-waiting.
2
u/Lonely-Restaurant986 Oct 15 '26
Does the environment you are working with provide a sleep function already? Some environments use different names. If so use that.
Does the environment you are working with have an update function that gets called every loop? If so use that
We want to help you, but we can’t help you specifically unless we know more about your problem.
1
u/Sckip974 Oct 15 '26
Look an Github bibliothèque (require)
timer.update(dt)every frame. A good choice for a game engine or LÖVE.TimerPoolclass, delayed calls (dcall), automatic repetition, and a manually-driven clock (pool:update).timer.performWithDelay, featuring pause/resume functionality via tags; derived from the Corona/LÖVE framework.1
u/weregod Oct 16 '26
If you writing code for an engine it should have some sort of sleep/delay function or timer system.
If you use some io library like luasocket they usually have poll function which can be used as sleep without fds.
You can access native posix functions using luaposix library.
if you don't have anything better use os.execute to call sleep (not sure if Windows has any equivalent for sleep)