Posted 24 April 2014 - 03:04 AM
After executing this code, until reboot all calls to turtle.up(), turtle.down(), ect will track the position of your turtle. All you have to do is call init() first, with the starting coordinates
This is especially useful when using the shell command "go" to move your turtle around, as changes to the coordinates will still be tracked!
It does this using the do…end command to create a local scope. It then stores a local reference to the old turtle.forward(), and binds turtle.forward() to a new closure that references the old turtle.forward() as an upvalue. (a process sometimes referred to as sandboxing) Future calls to turtle.forward() will call my function, which will in turn call the old turtle.forward() and then increment X or Z based on the value of FACE if it succeeded.
This is especially useful when using the shell command "go" to move your turtle around, as changes to the coordinates will still be tracked!
It does this using the do…end command to create a local scope. It then stores a local reference to the old turtle.forward(), and binds turtle.forward() to a new closure that references the old turtle.forward() as an upvalue. (a process sometimes referred to as sandboxing) Future calls to turtle.forward() will call my function, which will in turn call the old turtle.forward() and then increment X or Z based on the value of FACE if it succeeded.
SOUTH = 0
WEST = 1
NORTH = 2
EAST = 3
function init(x, y, z, face)
X = x
Y = y
Z = z
FACE = face
end
do
local function track_up()
Y = Y + 1
end
local function track_down()
Y = Y - 1
end
local function track_forward()
if FACE == SOUTH then
Z = Z + 1
elseif FACE == WEST then
X = X - 1
elseif FACE == NORTH then
Z = Z - 1
elseif FACE == EAST then
X = X + 1
end
end
local function track_back()
if FACE == SOUTH then
Z = Z - 1
elseif FACE == WEST then
X = X + 1
elseif FACE == NORTH then
Z = Z + 1
elseif FACE == EAST then
X = X - 1
end
end
local function track_left()
FACE = (FACE - 1) % 4
end
local function track_right()
FACE = (FACE + 1) % 4
end
local raw_up = turtle.up
local raw_down = turtle.down
local raw_forward = turtle.forward
local raw_back = turtle.back
local raw_left = turtle.turnLeft
local raw_right = turtle.turnRight
turtle.up = function()
if raw_up() then
track_up()
return true
else
return false
end
end
turtle.down = function()
if raw_down() then
track_down()
return true
else
return false
end
end
turtle.forward = function()
if raw_forward() then
track_forward()
return true
else
return false
end
end
turtle.back = function()
if raw_back() then
track_back()
return true
else
return false
end
end
turtle.left = function()
raw_left()
track_left()
end
turtle.right = function()
raw_right()
track_right()
end
end
Edited on 24 April 2014 - 03:05 AM