chore: refactor time functions into an util

This commit is contained in:
Kazhnuz 2021-04-05 09:48:59 +02:00
parent 1fb4c72098
commit 0c1f18ec64
3 changed files with 33 additions and 34 deletions

View file

@ -29,5 +29,6 @@ return {
graphics = require(cwd .. "graphics"), graphics = require(cwd .. "graphics"),
filesystem = require(cwd .. "filesystem"), filesystem = require(cwd .. "filesystem"),
table = require(cwd .. "table"), table = require(cwd .. "table"),
string = require(cwd .. "string") string = require(cwd .. "string"),
time = require(cwd .. "time"),
} }

View file

@ -0,0 +1,28 @@
local Math = require "core.utils.math"
Time = {}
Time.HOURS = 3600
Time.MINUTES = 60
Time.SEPARATOR = ":"
function Time.timestamp(hour, minute, seconds)
return (hour * Time.HOURS) + (minute * Time.MINUTES) + seconds
end
function Time.getFields(timestamp)
local hours = math.floor(timestamp / Time.HOURS)
local minutes = math.floor((timestamp % Time.HOURS) / Time.MINUTES)
local seconds = math.floor((timestamp % Time.MINUTES))
return hours, minutes, seconds
end
function Time.toString(timestamp)
local hours, minutes, seconds = Time.getFields(timestamp)
local str = Math.numberToString(hours, 2)
str = str .. Time.SEPARATOR .. Math.numberToString(minutes, 2)
str = str .. Time.SEPARATOR .. Math.numberToString(seconds, 2)
return str
end
return Time

View file

@ -199,41 +199,11 @@ function Game:update(dt)
end end
function Game:getTime() function Game:getTime()
local hours, minutes, seconds return utils.time.getFields(self.gametime)
seconds = math.floor(self.gametime)
minutes = math.floor(seconds / 60)
hours = math.floor(minutes / 60)
seconds = seconds % 60
minutes = minutes % 60
hours = hours
return seconds, minutes, hours
end end
function Game:getTimeString() function Game:getTimeString()
local string return utils.time.toString(self.gametime)
local seconds, minutes, hours = self:getTime()
local stringSeconds, stringMinutes, stringHours
if (seconds <= 9) then
stringSeconds = 0 .. seconds
else
stringSeconds = seconds
end
if (minutes <= 9) then
stringMinutes = 0 .. minutes
else
stringMinutes = minutes
end
if (hours <= 9) then
stringHours = 0 .. hours
else
stringHours = hours
end
string = stringHours .. ":" .. stringMinutes .. ":" .. stringSeconds
return string
end end
function Game:printTime() function Game:printTime()