Posted 08 December 2015 - 04:16 AM
I'm writing an API for digging with turtles that allows a program using it to keep track of where it is. However, I'm having trouble getting the global variables to work the way I want.
The idea is to run the functions like so:
-- This is an API used in programs
dist_x = 0
dist_y = 0
dist_z = 0
dist_r = 0
function update(n)
if n=="fwd" then
if dist_r == 0 then
dist_z = dist_z + 1
elseif dist_r == 90 then
dist_x = dist_x + 1
elseif dist_r == 180 then
dist_z = dist_z - 1
elseif dist_r == 270 then
dist_x = dist_x - 1
end
elseif n=="right" then
dist_r = dist_r + 90
elseif n=="left" then
dist_r = dist_r - 90
elseif n=="up" then
dist_y = dist_y + 1
elseif n=="down" then
dist_y = dist_y - 1
end
while dist_r >= 360 do
dist_r = dist_r - 360
end
while dist_r < 0 do
dist_r = dist_r + 360
end
--bug testing
print(dist_x)
print(dist_y)
print(dist_z)
print(dist_r)
end
function fwd(n)
local x
for x=1, n or 1 do
while not turtle.forward() do
turtle.dig()
turtle.attack()
end
update("fwd")
end
end
function up(n)
local x
for x=1, n or 1 do
while not turtle.up() do
turtle.digUp()
turtle.attackUp()
end
update("up")
end
if (n or 1) < 0 then
down(-n)
end
end
function down(n)
local x
for x=1, n or 1 do
while not turtle.down() do
turtle.digDown()
turtle.attackDown()
end
update("down")
end
if (n or 1) < 0 then
up(-n)
end
end
function left(n)
local x
for x=1, n or 1 do
turtle.turnLeft()
update("left")
end
for x=n or 1, -1 do
turtle.turnRight()
update("right")
end
end
function right(n)
local x
for x=1, n or 1 do
turtle.turnRight()
update("right")
end
for x=n or 1, -1 do
turtle.turnLeft()
update("left")
end
end
function dig()
while not turtle.dig() do end
end
The idea is to run the functions like so:
dig.up(2)
dig.right()
dig.fwd(6)
The "dig.dist_y" variable should be "2" because it went up two blocks, "dig.dist_x" should be "6", "dig.dist_r" should be "90", and "dig.dist_z" should still be "0". However, when I actually run the API, those variables always return "0". I presume this is because when the functions edit the variables, it just creates local variables that are cleared when the function terminates. How do I make sure I'm assigning the new values to the global variables?