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

[Turtle][Programming] Trouble with a variable

Started by jewelshisen, 10 January 2013 - 11:00 AM
jewelshisen #1
Posted 10 January 2013 - 12:00 PM
Here is my code:

rednet.open("right")
local x, y, z = gps.locate(2)
term.clear()
term.setCursorPos(1, 1)
print("Current Position: "..x..", "..y..", "..z)
print("Enter target X.")
local tx = tonumber(read())
print("Enter target Y.")
local ty = tonumber(read())
print("Enter target Z.")
local tz = tonumber(read())
print("Target Position: "..tx..", "..ty..", "..tz)
if ty <= 0 then
  print("Target is not valid")
  error()
end
if x > tx then
  local vx = x - tx
  elseif tx > x then
  local vx = tx - x
  else
  local vx = 0
end
if y > ty then
  local vy = x - ty
  elseif ty > y then
   local vy = ty - y
  else
  local vy = 0
end
if z > tz then
  local vz = z - tz
  elseif tz > z then
	local vz = tz - z
  else
	local vz = 0
end
print("Distance X: "..vx)
print("Distance Y: "..vy)
print("Distance Z: "..vz)


My issue is that it doesn't seem to be defining the vx, vy, and vz variables… Can anybody tell me why?
crazyguymgd #2
Posted 10 January 2013 - 12:05 PM
vx, vy, and vz are only accessible inside the scope they are initialize. An if, end block is it's own scope so you will only be able to access the variable inside that if,end block.
Kingdaro #3
Posted 10 January 2013 - 12:06 PM
By using "local" in the ifs, you're making the variable unique to only that if. Remove the "local" keywords from those variables when you define them, and if you feel the need to do so, localize them outside of the ifs.

local vx, vy, vz
if x > tx then
  vx = x - tx
elseif tx > x then
  vx = tx - x
else
  vx = 0
end
if y > ty then
  vy = x - ty
elseif ty > y then
  vy = ty - y
else
  vy = 0
end
if z > tz then
  vz = z - tz
elseif tz > z then
  vz = tz - z
else
  vz = 0
end
jewelshisen #4
Posted 10 January 2013 - 12:08 PM
Oh… I thought the local bit just made it local to that program. I will try what you suggest.

EDIT : Removing the local bit fixed it! Thank you tons!
Edited on 10 January 2013 - 11:10 AM
theoriginalbit #5
Posted 10 January 2013 - 12:42 PM
local makes it local to the scope. where the scope is a function, loop or program. after that scope finishes, so does the local variable.