92 lines
2.1 KiB
Lua
92 lines
2.1 KiB
Lua
-- Do not lose state when reset (chunkloading etc)
|
|
state = (function ()
|
|
local path = ".state"
|
|
local state_table = {}
|
|
|
|
if fs.exists(path) then
|
|
local f = fs.open(path, "r")
|
|
state_table = textutils.unserialize(f.readAll())
|
|
f.close()
|
|
end
|
|
|
|
return setmetatable({}, {
|
|
__index = state_table,
|
|
|
|
__newindex = function(self, k, v)
|
|
rawset(state_table, k, v)
|
|
local f = fs.open(path, "w")
|
|
f.write(textutils.serialize(state_table))
|
|
f.close()
|
|
end,
|
|
})
|
|
end)()
|
|
|
|
if state.x == nil or state.y == nil or state.z == nil or state.o == nil then
|
|
printError("[lib] position is not set")
|
|
printError("[lib] defaulting to 0, 0, 0, +z")
|
|
state.x = 0
|
|
state.y = 0
|
|
state.z = 0
|
|
state.o = 0
|
|
end
|
|
|
|
--[[
|
|
orientation:
|
|
0 = South (+z)
|
|
1 = West (-x)
|
|
2 = North (-z)
|
|
3 = East (+x)
|
|
]]
|
|
|
|
function getOrientation()
|
|
return ({"+z", "-x", "-z", "+x"})[1 + state.o]
|
|
end
|
|
|
|
function move(raw_move, position_update)
|
|
return function()
|
|
success, err = raw_move()
|
|
if not success then
|
|
return false, err
|
|
end
|
|
position_update()
|
|
return true
|
|
end
|
|
end
|
|
|
|
return {
|
|
state = state,
|
|
|
|
getOrientation = getOrientation,
|
|
|
|
fwd = move(turtle.forward, function()
|
|
if state.o == 1 or state.o == 3 then
|
|
state.x = state.x + ((state.o == 1) and -1 or 1)
|
|
elseif state.o == 0 or state.o == 2 then
|
|
state.z = state.z + ((state.o == 2) and -1 or 1)
|
|
end
|
|
end),
|
|
|
|
back = move(turtle.back, function()
|
|
if state.o == 1 or state.o == 3 then
|
|
state.x = state.x + ((state.o == 1 and 1 or -1))
|
|
elseif state.o == 0 or state.o == 2 then
|
|
state.z = state.z + ((state.o == 2) and 1 or -1)
|
|
end
|
|
end),
|
|
|
|
up = move(turtle.up, function()
|
|
state.y = state.y + 1
|
|
end),
|
|
|
|
down = move(turtle.down, function()
|
|
state.y = state.y - 1
|
|
end),
|
|
|
|
left = move(turtle.turnLeft, function()
|
|
state.o = (state.o - 1) % 4
|
|
end),
|
|
|
|
right = move(turtle.turnRight, function()
|
|
state.o = (state.o + 1) % 4
|
|
end),
|
|
} |