How do you refer to the player holding the gun in a SWEP?

To get the position of a player’s gun barrel, I think I need to use this bit of code that I took right from the gmod wiki.



local viewm = ply:GetViewModel()
local obj = viewm:LookupAttachment( 1 )
local muzzlepos = vm:GetAttachment( obj )


First of all, I don’t know how to refer to the player in a SWEP, and second of all, I don’t know what the “vm” in “vm:GetAttachment()” signifies.
Can anyone tell me how to refer to players in a SWEP, and maybe clarify how to use the Entity:GetAttachment() function?

self.Owner?

or self:GetOwner()

when i do that i get this error


 
[ERROR] gamemodes/terrortown/entities/weapons/aa.lua:36: attempt to index global 'self' (a nil value)
  1. unknown - gamemodes/terrortown/entities/weapons/aa.lua:36


self only works inside SWEP:* functions.



function SWEP.PrimaryAttack()
local viewm = self.Owner:GetViewModel()
local obj = viewm:LookupAttachment( 1 )
local muzzlepos = vm:GetAttachment( obj )
print(muzzlepos)
end

That error still occurs in this code.

You need to change SWEP.PrimaryAttack to SWEP:PrimaryAttack

It may be preferable use self:GetOwner(), since self.Owner just calls that anyway and has a comment about it being retired eventually https://github.com/garrynewman/garrysmod/blob/4eb9bb19dcfac06007691376ecaf2dbc56efa6b2/garrysmod/lua/includes/extensions/weapon.lua#L40

You need to use a colon (SWEP:PrimaryAttack()) instead of a period (SWEP.PrimaryAttack). The weapon is automatically passed as the first argument when you do so (which is what self is).

Thank you!