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

http://www.facepunch.com/showthread.php?p=24711186

Based on the above thread, it looks like one cannot use a function hooked to **[Gamemode.EntityTakeDamage

http://wiki.garrysmod.com/favicon.ico](wiki.garrysmod.com/?title=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)?

Thanks.

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

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.”

Thanks.

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

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

Just gotta pass 'em yourself.

Thanks.

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

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

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.