the second would make me happy
That's fairly simple, with a few caveats (see below):
Lua:
local next_time = os.time() + 3
while true do
if os.time() > next_time then
print(string.format("[%d] Hallo", os.time())) -- print also the current time
next_time = next_time + 3
end
end
The above code assumes that
os.time() returns the time in seconds (which is not guaranteed on all systems, as stated in the manual), and even if it does, the resolution is 1 second. As a consequence, the interval between successive prints will be 3 seconds +/- 1 second.
If you need more precise timing, you must resort to an external library that provides you with a function that gives you a monothonic time with a better resolution.
One alternative is to use
socket.gettime() from LuaSocket, and use it to replace os.time in the above code.
Another alternative is to use the
MoonTimers module (wrote by myself), that provides you with asynchronous timers. With timers, your example could be something like this:
Lua:
local timers = require("moontimers")
local function callback(tmr, exptime)
print(string.format("[%.3f] Hallo!", timers.now()))
tmr:start(exptime + 3)
end
-- Create a timer passing it the callback to execute at its expiration:
local T = timers.new(0, callback)
-- Start the timer:
T:start(timers.now() + 3)
-- Enter the event loop:
while true do
timers.trigger()
end
EDIT: fixed link to os.time() in Lua manual.