r/lua • • 9h 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

0 Upvotes

4 comments sorted by

3

u/ICON_4 8h ago edited 8h 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?

3

u/RelatableRedditer 8h 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.

1

u/Lonely-Restaurant986 5h 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 3h 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 TimerPool class, 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.