【问题标题】:Lua - If local x,y,z, and an x,y,z has been declared, are they the same or are they different?Lua - 如果已声明本地 x、y、z 和 x、y、z,它们是相同的还是不同的?
【发布时间】:2015-01-10 23:05:24
【问题描述】:
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

我在 Lua 中编程,我对变量的声明有点困惑。由于在 x,y,z 的一个实例上声明了“local”,然后在下面声明了 x,y,z 的另一个实例,这是否意味着它们是不同的变量还是相同?

谢谢。

【问题讨论】:

    标签: variables lua local


    【解决方案1】:

    在您显示的代码中,x,y,z 仅声明一次(作为本地),然后多次分配新值。其他的 x, y, z 都和局部的 x, y, z 在同一个范围内,并且出现在声明之后。下面是一些例子

    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 Tutorial 进行更深入的讨论。

    【讨论】:

    • 我想问你为什么添加了两个do-end但是你为什么这样做?如果你把它排除在外,会有什么不同吗?
    • do-end 对创建一个新范围。由于 x、y、z 是本地的,因此它们对于创建它们的 do-end 对是本地的,一旦我们到达该对的 end,它们就会变成垃圾。
    • @VeridisQuo 在您的示例中,x、y、z 在函数中声明,当您到达函数的end 时,它们就变成了垃圾。
    【解决方案2】:

    PIL 的第 4.2 节对此进行了详细讨论。因为您的local x,y,zx,y,z=... 位于相同的代码“块”中,所以它们是相同的。

    【讨论】:

      猜你喜欢
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多