2

I am really newbie in lua. I have this lua code

local gun_info = {
   g_sword={rate=0.5;spd=0;dmg=1;ammo=1;};
   g_pistol={rate=0.5;spd=5;dmg=1;ammo=40;};
   g_knife={rate=0.8;spd=5;dmg=1;ammo=1;};
   g_shuriken={rate=0.3;spd=5;dmg=1;ammo=40;};
   g_bomb={rate=0.8;spd=5;dmg=1;ammo=20;};
};

I just want get values of every ammo. Other properties are no needed.

for k, v in pairs(gun_info) do
  print(k, v[1], v[2], v[3], v[4], v[5])
end

this prints out whole tables but I need just value of ammos

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
javaprogrammer
  • 105
  • 1
  • 2
  • 11

1 Answers1

1

Use comma between table variables rather than semicolon. Using semicolon is not syntactically wrong but optional in Lua. Semicolon is usually used to separate multiple statements written in single line.

You can directly access the variable ammo by indexing the key of the table

for k, v in pairs(gun_info) do
    print(k, v.ammo)
end

v.ammo and v[ammo] are not same in Lua.

Note: The order in which the elements appear in traversal will not be the same as you defined and can produce different order each time. This is due to the way tables are implemented in Lua.

Ravi
  • 986
  • 12
  • 18
  • Thanks. If I improve your answer, can I use v[1].ammo if I need first ammo? – javaprogrammer Apr 17 '18 at 17:17
  • No. In your case you need to know the key. table in lua is an associative array. v[1] will be a different table index. You can access the first ammo by gun_info.g_sword.ammo – Ravi Apr 17 '18 at 17:28
  • So you mean if I need first ammo, I need loop gun_info.g_sword.ammo? not gun_info? Can't it be done more dynamically? because I think it is silly to loop five times if I need number of specific ammo – javaprogrammer Apr 17 '18 at 17:38
  • You no need to loop. If you know the keys you can directly access it. print(gun_info.g_sword.ammo) – Ravi Apr 17 '18 at 17:41