diff --git a/features/server.lua b/features/server.lua index d4c3f2b8..1227860c 100644 --- a/features/server.lua +++ b/features/server.lua @@ -1,6 +1,7 @@ --- See documentation at https://github.com/Refactorio/RedMew/pull/469 local Token = require 'utils.token' +local Global = require 'utils.global' local Public = {} @@ -9,6 +10,15 @@ function print(str) raw_print('[PRINT] ' .. str) end +local server_time = {secs = 0, tick = 0} + +Global.register( + server_time, + function(tbl) + server_time = tbl + end +) + local discord_tag = '[DISCORD]' local discord_raw_tag = '[DISCORD-RAW]' local discord_bold_tag = '[DISCORD-BOLD]' @@ -440,4 +450,27 @@ function Public.unban_non_sync(PlayerSpecification) game.unban_player(PlayerSpecification) end +--- Called by the web server to set the server time. +-- @param secs unix epoch timestamp +function Public.set_time(secs) + server_time.secs = secs + server_time.tick = game.tick +end + +--- Gets a table {secs:number, tick:number} with secs being the unix epoch timestamp +-- for the server time and ticks the number of game ticks it was set +-- @return table +function Public.get_time_data_raw() + return server_time +end + +--- Gets an estimate of the current server time as a unix epoch timestamp +-- The estimate may be slightly off if within the last minute the game has been paused, saving or overwise, +-- or the game speed has been changed. +-- @return number +function Public.get_current_time() + local diff = game.tick - server_time.tick + return server_time.secs + diff / game.speed +end + return Public diff --git a/features/server_commands.lua b/features/server_commands.lua index 3e860b07..49d28724 100644 --- a/features/server_commands.lua +++ b/features/server_commands.lua @@ -25,4 +25,6 @@ function ServerCommands.server_started() script.raise_event(Server.events.on_server_started, {}) end +ServerCommands.set_time = Server.set_time + return ServerCommands