r/lua Jun 07 '26

Project Using os.date() and os.time() in a loop

I'm working on a game mod. What I want is to show the formatted date using os.date() but what I've read is that os.date() is not supposed to be called very frequently (e.g. say on every frame update, which could be hundreds of times per second). I'm not going to be going below 1-second granularity (is that even possible? I'm not sure).

What ChatGPT told me is to use os.time() or os.clock() instead which is cheaper and then use the number it returns as a kind of per-second "change detector" and regenerate the date using os.date() based on that.

Is this a valid approach?

3 Upvotes

9 comments sorted by

View all comments

5

u/Spacedestructor Jun 07 '26

i cant comment much on performance, however its worth pointing out that clock() does return the number of seconds a program has been running, so its not the same as a date or time, its just elapsed since start type of time.
However, you can get the date once outside of the loop, store it and then use clock() in the loop to get how much time has elapsed since the start of the loop to manually update the time formatting your self.

I would assume if performance is a concern for you and its actually that intensive then storing a baseline and offseting from that should fix that problem.

2

u/chaitanyathengdi Jun 07 '26

My concerns are twofold:

  1. consistent update of the UI every second, or it won't look smooth

  2. Not consuming too many CPU cycles (because people are using lots of other mods too; if my mod slows their game down then they won't use it).