Search code examples
lualua-tablepico-8

Lua)) how to loop table of table and get a specific property?


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


Solution

  • 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.