Being able to use "self" in a hooked function...

Based on the above thread, it looks like one cannot use a function hooked to **[Gamemode.EntityTakeDamage](** and be able to use both “self” and the damaged entity (the “ent” argument) in the same function.

Is this true, or is there a way to refer to “self” while still being able to use the “ent” argument (The damaged entity)?


[lua]function ENT:MyFunction()
print(“Hello, World!”);

hook.Add(“Think”,self:EntIndex() … “PrintInfo”,ENT.MyFunction) – THIS IS WRONG

hook.Add(“Think”,self:EntIndex() … “PrintInfo”,function() ENT:MyFunction() end) – THIS IS RIGHT[/lua]

The issue is, when you pass the ENT.MyFunction variable as an argument to a think hook, it just calls the function as a regular function. You have to use a colon “:” in order to have “self” passed an implicit argument.

But wouldn’t that cut out the first argument, “ent”? I want to use both “self” and “ent.”


[lua]function ENT:DamageStuff( ent, inf, attack, amnt, dmg )
– things

function ENT:Init()
hook.Add(“EntityTakeDamage”,self:EntIndex() … “blargh”,function(ent,inf,attack,amnt,dmg) self:DamageStuff(ent,inf,attack,amnt,dmg); end)

Just gotta pass 'em yourself.


One question though, why would I need to hook the function in ENT.Init?

You shouldn’t. Hook it outside of any function.

Wouldn’t you need a separate hook for each entity?

Aye I see now, but then you’d need a unique hook id.

I still can’t figure why you would want self in a hook, I’m sure there are better solutions.

Maybe in autorun

local function RunSentFunction(ply, text, teamchat, plydead)
for k, v in pairs(ents.FindByClass(“ent_fred”)) do
v:DoFunction(ply, text, teamchat, plydead)
hook.Add(“PlayerSay”, “FredRunFunction”, RunSentFunction)

Just seems more efficient than having a load of hooks… just a hunch though, I don’t have any evidence for that.

Exactly what I meant, this is a way more elegant solution.

Actually, the entity I’m doing this with only hooks with one unique name… but I’ll keep this in mind.

Thanks, all of ya.