Our first example demonstrates how to work with time and durations in Lua. Here’s the full source code:
Let’s go through this code:
We start by importing the os module, which provides time-related functions in Lua.
We define a helper function p to make printing easier.
We get the current time using os.time().
We create a specific time using os.time() with a table of time components.
We extract various components of the time using os.date("*t", time), which returns a table with the time components.
We compare times using the standard comparison operators.
We calculate the difference between two times using os.difftime().
We show how to convert the time difference to different units.
Finally, we demonstrate how to add or subtract time from a given time.
When you run this script, you’ll see output similar to this:
Note that the exact output will depend on the current time when you run the script.
In Lua, time handling is somewhat simpler compared to some other languages. It doesn’t have a separate Duration type, so we work directly with seconds for time differences. Also, Lua’s standard library doesn’t provide as many built-in time manipulation functions, so for more complex time operations, you might need to write your own functions or use additional libraries.