• Print

Author Topic: Giving Table Values  (Read 4986 times)

0 Members and 1 Guest are viewing this topic.

Offline BlueNova

  • Full Member
  • ***
  • Posts: 113
  • Karma: 13
  • The most powerful force in the universe.
Giving Table Values
« on: May 02, 2017, 12:44:03 pm »
So I just wanted to know if it's possible to give the values of a table, all of them that is.

If I remember correctly I don't think this will work.

Code: Lua
  1. weapons = { "weapon_physgun", "weapon_rpg" }
  2.  
  3. ply:Give( weapons )

Fairly confident that wouldn't work so is there a way to give all the values in a table or no? Thanks

Offline MrPresident

  • Ulysses Team Member
  • Hero Member
  • *****
  • Posts: 2727
  • Karma: 430
    • |G4P| Gman4President
Re: Giving Table Values
« Reply #1 on: May 02, 2017, 12:56:58 pm »
You need to iterate through the table.
Code: Lua
  1. local weapons = { "weapon_physgun", "weapon_rpg" }
  2.  
  3. for k, v in pairs( weapons ) do
  4.    ply:Give( v )
  5. end
  6.  

Offline BlueNova

  • Full Member
  • ***
  • Posts: 113
  • Karma: 13
  • The most powerful force in the universe.
Re: Giving Table Values
« Reply #2 on: May 02, 2017, 01:04:01 pm »
Heh, now I'm ashamed for not seeing something that obvious. Thnx

Offline iViscosity

  • Respected Community Member
  • Hero Member
  • *****
  • Posts: 803
  • Karma: 58
Re: Giving Table Values
« Reply #3 on: May 02, 2017, 03:24:52 pm »
Alternatively, you could iterate through it differently:

Code: Lua
  1. local weapons = { "weapon_physgun", "weapon_rpg" }
  2.  
  3. for i = 1, #weapons do
  4.     ply:Give( weapons[ i ] )
  5. end
  6.  

But to be honest, I use pairs more often, especially if the keys aren't numeric or in order.
I'm iViscosity. I like gaming and programming. Need some help? Shoot me PM.

Offline BlueNova

  • Full Member
  • ***
  • Posts: 113
  • Karma: 13
  • The most powerful force in the universe.
Re: Giving Table Values
« Reply #4 on: May 02, 2017, 03:27:37 pm »
Thing is the first answer didn't work, forgot that ply:Give() wants a string value not a table value. I'll play with using numbers, etc until I get somewhere.

Offline MrPresident

  • Ulysses Team Member
  • Hero Member
  • *****
  • Posts: 2727
  • Karma: 430
    • |G4P| Gman4President
Re: Giving Table Values
« Reply #5 on: May 02, 2017, 06:01:53 pm »
my method would have worked. It shouldn't return a table value.

v in the case of a k,v pairs loop would return the value inside the table.. which in the case of the example provided would be a string.

Offline MrPresident

  • Ulysses Team Member
  • Hero Member
  • *****
  • Posts: 2727
  • Karma: 430
    • |G4P| Gman4President
Re: Giving Table Values
« Reply #6 on: May 02, 2017, 06:03:10 pm »
Example console output:

lua_run local testtab = { "test1", "test2" } for k, v in pairs( testtab ) do print(v) end
       
test1
test2

  • Print