feat(robot): add config.onSave function

This commit is contained in:
Guillaume ARM 2024-05-25 23:43:35 +02:00
parent f6ab6d6f77
commit ffccce4700

View File

@ -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