Veridis Quo
Veridis Quo

Reputation: 57

Lua - If local x,y,z, and an x,y,z has been declared, are they the same or are they different?

function PedsPrepareConversation(ped1,ped2,distance,walkSpeed)
PlayerSetPunishmentPoints(0)
  if PedGetWeapon(gPlayer) == 437 then
    PedSetWeapon(gPlayer,-1)
  end
  if PedIsInAnyVehicle(gPlayer) then
    PedWarpOutOfCar(gPlayer)
  end
  PedStop(ped2)
  local x,y,z = PedGetPosXYZ(ped2)
  PedMoveToXYZ(ped1,walkSpeed,x,y,z)
  local r1 = x + distance
  local r2 = y + distance
  local r3 = x - distance
  local r4 = y - distance
  x,y,z = PedGetPosXYZ(ped1)
  PedFaceXYZ(ped2,x,y,z)
  repeat
 Wait(0)
  until PedInRectangle(ped1,r1,r2,r3,r4)
  PedStop(ped1)
  x,y,z = PedGetPosXYZ(ped2)
  PedFaceXYZ(ped1,x,y,z)
  x,y,z = PedGetPosXYZ(ped1)
  PedFaceXYZ(ped2,x,y,z)
end

I was programming in Lua and I was a bit confused at the declaration of the variables. Since "local" has been declared on one instance of x,y,z and then another instance of x,y,z has been declared below does that mean that they are different variables or are they the same?

Thanks.

Upvotes: 2

Views: 319

Answers (2)

Oliver
Oliver

Reputation: 29483

This is discussed at length in section 4.2 of PIL. Because your local x,y,z is in the same "block" of code as the x,y,z=..., they are the same.

Upvotes: 0

ryanpattison
ryanpattison

Reputation: 6251

In the code you are showing x,y,z are only declared once (as local) and then are assigned new values multiple times. The other x, y, z are all in the same scope as the local x, y, z and appear after the declaration. Here are some examples

do -- new scope
  local x,y,z = 'a','b','c' -- declared local
  print(x, y, z)   -- prints a b c
  do
    x,y,z = 1,2,3   -- new scope, but still referring to the local x, y, z (higher scope)
    print(x, y, z)  -- prints 1 2 3
  end
  print(x, y, z) -- prints 1 2 3 (modified the original)
end -- end local x, y, z scope (now they are garbage)
-- global scope, no x, y, z is defined here 
print(x, y, z)   -- prints nil nil nil 

Scope is a big concept so check out Scope Tutorial for a more thorough discussion.

Upvotes: 1

Related Questions