I made a few tweaks to it.
- Made it return a useful value. The weapon ID is already known since it is being passed to the function, so why return it? Instead, return the entity ID since this is unknown information and the scripter may want to use it for other stuff. If the checks fail, the function returns -1.
- Renamed wp_id variable to something that makes sense since it is holding the weapon name, not id.
- Added additional checks to prevent errors. Weapon ID must fall within a range that will make get_weaponname() not error. Clip and bpammo must be >= 0.
- Eliminated if-else and redundant code by getting the entity index in one line based on if the player has it already or if it is given to the player.
- Final safety check to make sure an entity index is in the variable before using cs_set ammos.
- Added grenade support.
- Fixed C4 support and added code to conditionally give clip/bp ammo.
PHP Code:
give_user_weapon( index , iWeaponTypeID , iClip=0 , iBPAmmo=0 )
{
if ( !( CSW_P228 <= iWeaponTypeID <= CSW_P90 ) || ( iClip < 0 ) || ( iBPAmmo < 0 ) || !is_user_alive( index ) )
return -1;
new szWeaponName[ 20 ] , iWeaponEntity , GrenadeBits;
GrenadeBits = ( ( 1 << CSW_HEGRENADE ) | ( 1 << CSW_FLASHBANG ) | ( 1 << CSW_SMOKEGRENADE ) | ( 1 << CSW_C4 ) );
get_weaponname( iWeaponTypeID , szWeaponName , charsmax( szWeaponName ) );
if ( ( iWeaponEntity = user_has_weapon( index , iWeaponTypeID ) ? find_ent_by_owner( -1 , szWeaponName , index ) : give_item( index , szWeaponName ) ) > 0 )
{
if ( iClip && !( GrenadeBits & ( 1 << iWeaponTypeID ) ) )
cs_set_weapon_ammo( iWeaponEntity , iClip );
if ( iWeaponTypeID == CSW_C4 )
cs_set_user_plant( index , 1 , 1 );
else if ( iBPAmmo )
cs_set_user_bpammo( index , iWeaponTypeID , iBPAmmo );
}
return iWeaponEntity;
}
__________________