消除Lua中表的前缀

Ste*_*flf 1 lua

function1
   weaponsList.earth = {weapon_type='regular',fireTime=0, fireRate=0.7, speed = 250, img = nil}
end
Run Code Online (Sandbox Code Playgroud)

你可以做这样的事情来访问一个子成员.

  "using weaponsList,earth"
     fireTime = 2
     fireRate = 2
     speed = 2
   end
Run Code Online (Sandbox Code Playgroud)

而不是必须这样做

   weaponsList.earth.fireTime = 2
   weaponsList.earth.fireRate = 2
   weaponsList.earth.speed = 2
Run Code Online (Sandbox Code Playgroud)

不知道这是什么叫,但我已经在C或C++中看到了.有没有办法在Lua中做到这一点,它叫什么?

md5*_*d5i 7

您可以执行以下操作,但要小心.将_ENV设置为您的表意味着,在该范围内,您无法在表外看到.

do local _ENV = weaponsList.earth
  fireTime = 2
  fireRate = 2
  speed = 2
end
Run Code Online (Sandbox Code Playgroud)

另一种可能更好的方法是:

do local e = weaponsList.earth
  e.fireTime = 2
  e.fireRate = 2
  e.speed = 2
end
Run Code Online (Sandbox Code Playgroud)

在进行多次操作之前将嵌套表分配给局部变量实际上是基本Lua实现中的优化,因为它不需要在每次使用中取消引用外部表.