Calculate x in x seconds

Asked

Viewed 257 times

2

I have this code that calculates in 1 second in 1 second between a certain time and then insert into a table. Instead of calculating every 1 second, how can I calculate, for example, every 5 seconds?

for y = horaInicial, horaFinal-1 do
    hora = tostring(math.floor(y / (3600)))
    minuto = tostring(math.floor((y - hora * (3600)) / (60)))
    segundo =  tostring(math.floor(y - hora * (3600) - minuto * (60)))

end
  • Explain better what this "calculate in 5 seconds".

  • This code inserts it into a 1-in-1-second table between the start time and the end time. I wanted you to calculate with a certain secondary, as for example 5.

  • Full coded entry: http://answall.com/questions/49812/insert

1 answer

4


Just add a third parameter to the for indicated the jumps that must be given. Thus:

function str2time(hora) 
    return tonumber(string.sub(hora, 1, 2)) * 3600 + tonumber(string.sub(hora, 4, 5)) * 60 + tonumber(string.sub(hora, 7, 8))
end

hora_array = {"20:03:02", "20:03:35"}
horaInicial = str2time(hora_array[1])
horaFinal = str2time(hora_array[2])
hora_array = {}
for i = horaInicial, horaFinal - 1, 5 do --note o 5 aqui --------------------------
    hora = math.floor(i / 3600)
    minuto = math.floor((i - hora * 3600) / 60)
    segundo =  math.floor(i - hora * 3600 - minuto * 60)
    table.insert(hora_array, string.format("%02d:%02d:%02d", hora, minuto, segundo))
end

for i, v in ipairs(hora_array) do print(v) end

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.