I am trying to make an API. It is meant to provide movement functions for turtles while keeping track of their relative position.
This is the API:
Spoiler
--[[
This API is created to provide Turtles functions to keep
track of their relative location while moving around.
Basically, after moving or turning I would like to save this information in a file.
Just in case the server shuts down or the chunk unloads.
]]--
--current location--create variables
-- used to be "local x = 0" but that didn't work either
x = 0
y = 0
z = 0
--current direction
d = 0
--[[
support functions:
getLocation FromFile
]]--
--getLocation
function getLocation()
locationFile = fs.open("location", "r")
directionFile = fs.open("direction", "r")
d = tonumber(locationFile.readAll())
gx, gy, gz = locationFile.readAll():match("([^,]+),([^,]+), ([^,]+)")
x, y, z = tonumber(gx), tonumber(gy), tonumber(gz)
locationFile.close()
directionFile.close()
end
--setLocation and direction
function setLocation()
location = "" .. x .. "," .. y .. "," .. z --this is line 33
direction = "" .. d
locationFile = fs.open("location", "w")
locationFile.write(location)
locationFile.close()
directionFile = fs.open("direction", "w")
directionFile.write(direction)
directionFile.close()
end
--movement functions
function registerMove(amount)
if d == 0 then
y = y+amount
elseif d == 1 then
x = x+amount
elseif d == 2 then
y = y-amount
elseif d == 3 then
x = x-amount
end
end
function move(amount)
for x = 0, amount-1, 1 do
getLocation()
if turtle.forward() then
registerMove()
setLocation()
end
end
end
function moveV(amount)
for x = 0, amount-1, 1 do
getLocation()
if turtle.forward() then
z = z+amount
setLocation()
end
end
end
function turnLaft()
getLocation()
turtle.turnLeft()
if d > 1 then
d = d-1
else
d = 4
end
setLocation()
end
function turnRaight()
getLocation()
turtle.turnRight()
if d < 4 then
d = d+1
else
d = 1
end
setLocation()
end
function init()
x = 0
y = 0
z = 0
d = 0
setLocation()
end
this is the program I use to test moving forward for 5 blocks.
os.loadAPI("movementAPI")
movementAPI.init()
movementAPI.move(5)
I get the following error:
MovementAPI: 33 : attempt to concatenate string and nil
line 33 shows the following code
location = "" .. x .. "," .. y .. "," .. z
I understand that I am probably not using the references to x, y, z and d properly… however I cannot figure out how to do it x)
Could anyone give me some tips?
Cheers!
Chris