Redefining a base function - Stack overflow

So I’m trying to redefine the old ply:Give( weapon ) function for my own purposes, but the problem is since the new function calls itself I get a stack overflow. I’m not sure how to stop it from doing this.

This is basically what I have now.


local meta = FindMetaTable( "Player" )
	function meta:Give( wep )
		//Doing some new stuff here
		self:Give( wep )
	end

I’d think this would work, but I get “attempt to call method ‘oldgive’ (a nil value)”.


local meta = FindMetaTable( "Player" )
	local oldgive = meta.Give
	function meta:Give( wep )
		//Doing some new stuff here
		self:oldgive( wep )
	end

Any tips?

local meta = FindMetaTable( “Player” )
local oldgive = meta.Give
function meta:Give( wep )
//Doing some new stuff here
oldgive( self, wep )
end

This works.
I don’t understand enough about objects in lua to know why it doesn’t work with the colon syntax, though.
Time to read up, I suppose.

Thanks for the tip.

It’s because you didn’t add the function “oldgive” to the entity or meta object, you just made it a local variable. So you just need to call it like a local variable.

Okay, this is strange. It’s stopped working now.


local meta = FindMetaTable( "Player" )
	function meta:Give( wep )
		if !oldgive then oldgive = meta.Give end
		//Do some new stuff
		oldgive(self,wep)
	end

This is giving me stack overflows, again. I have no idea why.

Edit: I figured it out 5 minutes after posting it: Defining oldgive inside the new Give function just sets oldgive to the new Give which will obviously lead to endless recursion and thus an overflow.

Just moving that if statement out of the function fixes it.
Am leaving this code here for posterity.


local meta = FindMetaTable( "Player" )
	if !meta.oldgive then meta.oldgive = meta.Give end
	function meta:Give( wep )
		if !self.AllowedWeapons then self.AllowedWeapons = {} end
		if !table.HasValue(self.AllowedWeapons, wep) then
			table.insert( self.AllowedWeapons, wep )
		end
		self:oldgive(wep)
	end

Yeah, I’m dumb