This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
eddieo's profile picture

Help with a function

Started by eddieo, 01 July 2012 - 04:52 PM
eddieo #1
Posted 01 July 2012 - 06:52 PM
Would one of you Pros please help a stupid wannbe with a function.

function getturtlepos()
cp = {"West","North","East","South"}
rednet.open("right")
ox,oy,oz = gps.locate(10)
turtle.forward()
fx,fy,fz = gps.locate(10)
turtle.back()
rednet.close("right")
if fx > ox then
oth = 3 --East
end
if fx < ox then
oth = 1 --West
end
if fz > oz then
oth = 4 --South
end
if fz < oz then
oth = 2 --North
end
term.clear()
term.setCursorPos(1,1)
print(os.getComputerLabel())
print("Current Position Is")
print("X = ",ox)
print("Y = ",oy)
print("Z = ",oz)
print("Currently Facing")
print(oth ," or ",cp[oth])
end
I want to pass oth ox oy and oz out of the function so they can be used later. I have tried and can only get oth to work. I know return is used somehow but I am stumped. FYI this function does work as is, just to let you know
MysticT #2
Posted 01 July 2012 - 07:17 PM
You need to return them, using return:

local function f()
  return value1, value2, ..., valueN
end

I added it and made some changes. It's good practice to use local inside functions.

function getturtlepos()
  local cp = {"West","North","East","South"}
  rednet.open("right")
  local ox,oy,oz = gps.locate(10)
  turtle.forward()
  local fx,fy,fz = gps.locate(10)
  turtle.back()
  rednet.close("right")
  local oth
  if fx > ox then
	oth = 3 --East
  elseif fx < ox then
	oth = 1 --West
  end
  if fz > oz then
	oth = 4 --South
  elseif fz < oz then
	oth = 2 --North
  end
  term.clear()
  term.setCursorPos(1,1)
  print(os.getComputerLabel())
  print("Current Position Is")
  print("X = ",ox)
  print("Y = ",oy)
  print("Z = ",oz)
  print("Currently Facing")
  print(oth ," or ",cp[oth])
  return ox, oy, oz, oth
end

Then, you can use it like:

local x, y, z, d = getturtlepos()

EDIT:
You could also make the variables global to the program/api:

local x, y, z, h = 0, 0, 0, 0

function getturtlepos()
  local cp = {"West","North","East","South"}
  rednet.open("right")
  x, y, z = gps.locate(10)
  turtle.forward()
  local fx, fy, fz = gps.locate(10)
  turtle.back()
  rednet.close("right")
  if fx > x then
	h = 3 --East
  elseif fx < x then
	h = 1 --West
  end
  if fz > z then
	h = 4 --South
  elseif fz < z then
	h = 2 --North
  end
  term.clear()
  term.setCursorPos(1,1)
  print(os.getComputerLabel())
  print("Current Position Is")
  print("X = ",x)
  print("Y = ",y)
  print("Z = ",z)
  print("Currently Facing")
  print(h ," or ",cp[h])
end
eddieo #3
Posted 01 July 2012 - 08:04 PM
Thank you very much