From ffccce4700a6ff16d3a82f1ae574154b3528cc07 Mon Sep 17 00:00:00 2001 From: Guillaume ARM Date: Sat, 25 May 2024 23:43:35 +0200 Subject: [PATCH] feat(robot): add config.onSave function --- libs/robot.lua | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/libs/robot.lua b/libs/robot.lua index faa4739..7f8b0f5 100644 --- a/libs/robot.lua +++ b/libs/robot.lua @@ -10,11 +10,16 @@ local DEFAULT_CONFIG = { stateFilePath = ROBOT_DEFAULT_STATE_FILE } +local function identity(x) + return x +end + local function getConfig(givenConfig) return { autosave = givenConfig.autosave or DEFAULT_CONFIG.autosave, autoload = givenConfig.autoload or DEFAULT_CONFIG.autoload, - stateFilePath = givenConfig.stateFilePath or DEFAULT_CONFIG.stateFilePath + stateFilePath = givenConfig.stateFilePath or DEFAULT_CONFIG.stateFilePath, + onSave = givenConfig.onSave or identity } end @@ -28,8 +33,7 @@ local function createDefaultState() } end -local saveRobotState = function(stateFile, state) - stateFile = stateFile or ROBOT_DEFAULT_STATE_FILE +local saveRobotState = function(stateFile, onSave, state) state = state or createDefaultState() local file = fs.open(stateFile, 'w') @@ -37,18 +41,17 @@ local saveRobotState = function(stateFile, state) error('saveRobotState: cannot open ' .. stateFile .. ' file!') end - file.write(textutils.serializeJSON(state)) + file.write(textutils.serializeJSON(onSave(state))) file.close() return state end -local loadRobotState = function(stateFile) - stateFile = stateFile or ROBOT_DEFAULT_STATE_FILE +local loadRobotState = function(stateFile, onSave) local file = fs.open(stateFile, 'r') if not file then - return robot.saveRobotState(stateFile) + return robot.saveRobotState(stateFile, onSave) end local serializedRobotState = file.readAll() @@ -57,7 +60,7 @@ local loadRobotState = function(stateFile) local parsedResult = textutils.unserializeJSON(serializedRobotState) if not parsedResult then - return robot.saveRobotState(stateFile) + return robot.saveRobotState(stateFile, onSave) end return parsedResult @@ -68,7 +71,7 @@ local getAutoSave = function(config, state) if config.autosave then autoSave = function() - saveRobotState(config.stateFilePath, state) + saveRobotState(config.stateFilePath, config.onSave, state) end end @@ -192,11 +195,11 @@ api.create = function(state, givenConfig) end robot.saveState = function() - return saveRobotState(config.stateFilePath, state) + return saveRobotState(config.stateFilePath, config.onSave, state) end robot.loadState = function(stateFile) - return loadRobotState(config.stateFilePath) + return loadRobotState(config.stateFilePath, config.onSave) end return robot