feat(robot): add saveRobotState and loadRobotState methods
This commit is contained in:
parent
022f778f0b
commit
494c32faf6
@ -30,7 +30,9 @@ upgrade
|
|||||||
|
|
||||||
```
|
```
|
||||||
rm config
|
rm config
|
||||||
|
rm data
|
||||||
rm startup.lua
|
rm startup.lua
|
||||||
rm .minerstate
|
rm .minerstate
|
||||||
|
rm .robotstate
|
||||||
upgrade
|
upgrade
|
||||||
```
|
```
|
||||||
|
|||||||
@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
local api = {}
|
local api = {}
|
||||||
|
|
||||||
|
local ROBOT_DEFAULT_STATE_FILE = '/.robotstate'
|
||||||
|
|
||||||
local function createDefaultState()
|
local function createDefaultState()
|
||||||
return {
|
return {
|
||||||
y = 0,
|
y = 0,
|
||||||
@ -12,7 +14,8 @@ local function createDefaultState()
|
|||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
api.create = function(state)
|
api.create = function(state, defaultStateFile)
|
||||||
|
defaultStateFile = defaultStateFile or ROBOT_DEFAULT_STATE_FILE
|
||||||
state = state or createDefaultState()
|
state = state or createDefaultState()
|
||||||
|
|
||||||
local mutateRobotPosition = function(isBackward)
|
local mutateRobotPosition = function(isBackward)
|
||||||
@ -113,6 +116,40 @@ api.create = function(state)
|
|||||||
return state
|
return state
|
||||||
end
|
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
|
return robot
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user