Return to Main Page

Getting a player weapons

Page white text.png Description:Getting a player entity with different ways.
link=User:Dim1xs Author:Dim1xs
Calendar.png Created:May 3nd 2024

The Beggining

Fast tutorial that will show you, how to get all items/weapons from player inventory.

Make sure you have lastest HL2GMED version.

Starting from script

Make sure that you have already read this tutorial.

CBasePlayer:GetWeapon(2)
               
This function is returning weapon from inventory by index/id.

Each weapon has own index in player inventory.
local ply = UTIL.PlayerByIndex(1)
print(ply:GetWeapon(2))
               

Output:

CBaseCombatWeapon: 70 weapon_pistol
               
For getting a table with all player weapons, you can use this loop method:

Output:

local tWeapons = {}
local ply = UTIL.PlayerByIndex(1)
local count = ply:WeaponCount()
for i=0,count do
   i=i+1
   local weapon = ply:GetWeapon(i)
   if ToBaseEntity(weapon) ~= NULL then
      table.insert(tWeapons, weapon)
   end
end      
               
BUG! For some reasons, source engine also uses 0 number for weapons index, but lua can't have 0 key in table, so this can be inaccurate.

If you want to use it in function, add return tWeapons on function end and player on function arguments, And you will be able to use this function to get all weapons from different player.

Thank you for reading this article, see ya later!

JOIN HL2GMED DISCORD SERVER!