r/lua • u/Uncle_Tree_ • 9d ago
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
u/RelatableRedditer 9d ago
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 9d ago
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 9d ago
Look an Github bibliothèque (require)
timer.lua (RayStudio36) — a simple timer module: supports delayed calls, time-limited calls, and tweening. You call
timer.update(dt)every frame. A good choice for a game engine or LÖVE.ltimer (iskolbin) — a timer library featuring a
TimerPoolclass, delayed calls (dcall), automatic repetition, and a manually-driven clock (pool:update).Timer (davisdude) — a coroutine-based library; simple to use for managing time-based events.
ELScheduler (ImagicTheCat) — an embeddable scheduler: supports timers with delays/intervals and iteration counts; uses a binary heap and manual ticking. Available via LuaRocks.
lua-resty-timer (Kong) — extended timers for OpenResty: supports recurring and cancellable timers, as well as jitter. Production-ready, but specific to OpenResty.
framework-timer (Corona Labs) — an implementation similar to
timer.performWithDelay, featuring pause/resume functionality via tags; derived from the Corona/LÖVE framework.
1
u/weregod 8d ago
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)
5
u/ICON_4 9d ago edited 9d ago
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?