Jump to content




[Turtle][Programming] Trouble with a variable

turtle lua

4 replies to this topic

#1 jewelshisen

  • Members
  • 164 posts

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?

#2 crazyguymgd

  • Members
  • 139 posts
  • LocationUSA

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.

#3 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

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


#4 jewelshisen

  • Members
  • 164 posts

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 by jewelshisen, 10 January 2013 - 12:10 PM.


#5 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users