feat(robot): add saveRobotState and loadRobotState methods
This commit is contained in:
parent
022f778f0b
commit
494c32faf6
@ -30,7 +30,9 @@ upgrade
|
||||
|
||||
```
|
||||
rm config
|
||||
rm data
|
||||
rm startup.lua
|
||||
rm .minerstate
|
||||
rm .robotstate
|
||||
upgrade
|
||||
```
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user