From 494c32faf607cf26bff37c2ac63b11dca414ec17 Mon Sep 17 00:00:00 2001 From: Guillaume ARM Date: Sat, 25 May 2024 23:22:05 +0200 Subject: [PATCH] feat(robot): add saveRobotState and loadRobotState methods --- README.md | 2 ++ libs/robot.lua | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fd6738a..4df08b5 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,9 @@ upgrade ``` rm config +rm data rm startup.lua rm .minerstate +rm .robotstate upgrade ``` diff --git a/libs/robot.lua b/libs/robot.lua index a33534e..0fc7ee8 100644 --- a/libs/robot.lua +++ b/libs/robot.lua @@ -2,6 +2,8 @@ local api = {} +local ROBOT_DEFAULT_STATE_FILE = '/.robotstate' + local function createDefaultState() return { y = 0, @@ -12,7 +14,8 @@ local function createDefaultState() } end -api.create = function(state) +api.create = function(state, defaultStateFile) + defaultStateFile = defaultStateFile or ROBOT_DEFAULT_STATE_FILE state = state or createDefaultState() local mutateRobotPosition = function(isBackward) @@ -113,6 +116,40 @@ api.create = function(state) return state end + robot.saveRobotState = function(stateFile) + stateFile = stateFile or defaultStateFile + local file = fs.open(stateFile, 'w') + + if not file then + error('saveRobotState: cannot open ' .. stateFile .. ' file!') + end + + file.write(textutils.serializeJSON(state)) + file.close() + + return state + end + + robot.loadRobotState = function(stateFile) + stateFile = stateFile or defaultStateFile + local file = fs.open(stateFile, 'r') + + if not file then + return robot.saveRobotState(stateFile) + end + + local serializedRobotState = file.readAll() + file.close() + + local parsedResult = textutils.unserializeJSON(serializedRobotState) + + if not parsedResult then + return robot.saveRobotState(stateFile) + end + + return parsedResult + end + return robot end