Peanut Jams
Peanut Jams

Reputation: 384

How to automatically check time?

Is it possible to automatically check time then execute certain codes?

timer = os.date('%H:%M:%S', os.time() - 13 * 60 * 60 )

if timer == "18:04:40" then
   print("hello")
end

I am trying to print hello on "18:04:40" everyday (os.date's time) without setting up a timer (which counts how much time past since the program's initiation) as I can't run the program 24 hours non-stop...

Thanks for reading.

Upvotes: 0

Views: 285

Answers (2)

koyaanisqatsi
koyaanisqatsi

Reputation: 2813

Lua has to check the time in some way.
Without a loop that can be realized with debug.sethook().
Example with Lua 5.1 typed in an interactive Lua (lua -i)...

> print(_VERSION)
Lua 5.1
> debug.sethook() -- This clears a defined hook
> -- Next set up a hook function that fires on 'line' events
> debug.sethook(function() local hour, min, sec = 23, 59, 59 print(os.date('%H:%M:%S', os.time({year = 2021, month = 12, day = 11, hour = hour, min = min, sec = sec}))) end, 'l')
-- just hit return/enter or do other things
23:59:59

5.9 - The Debug Library
https://www.lua.org/manual/5.1/manual.html#5.9

Upvotes: 0

RH2O
RH2O

Reputation: 11

This may not be the best solution but, when using a library like love2d for example you could run something like this:


function love.update(dt)
 timer = os.date('%H:%M:%S', os.time() - 13 * 60 * 60 )
 if timer >= value then 
  --stuff here
 end
end

Or if you wanna make it so you have a whole number something like

tick = 0
function love.update(dt)
 tick = tick + dt 
 if tick > 1 then 
  timer = os.date('%H:%M:%S', os.time() - 13 * 60 * 60 )
  if timer >= value then 
   --stuff here
  end
 end
end

Upvotes: 1

Related Questions