SetHealth() refuses to work, defined variable is nil

Hey, guys.
So, I made this function for my cannibalism thingamajiggy


hook.Add("KeyPress", "deathRagdollUse", function()
	if LocalPlayer():KeyDown(IN_USE) then
		ply = LocalPlayer()

		local trace = ply:GetEyeTrace()
		if not IsValid(trace.Entity) or (ply:EyePos():Distance(trace.Entity:GetPos()) > 100) then return end

		if trace.Entity:GetClass() == "prop_ragdoll" and trace.Entity.player != "" then
			local Body = trace.Entity
			if Body.Damage == nil then Body.Damage = 50 end
			
			if Body.Once then return end
			if ply:Team() ~= TEAM_HOBO then return end
			if Body.Damage <= 0 then Body:Remove() return end

			Body.Damage = Body.Damage - 1
			MsgN(ply:Health())
			local heal = 2
			local hp = ply:GetMaxHealth(), ply:Health() + heal
			ply:SetHealth(hp)
			if ply:Health() > 100 then ply:SetHealth(100) MsgN("Setting health to 100") end
			Body.Once = true;
			timer.Simple(0.5, function() Body.Once = false end)
		end
	end
end)

The problem is, it refuses to set player’s health. Even if I type in ply:SetHealth(100), nothing will happen.
Another problem is it refuses to read the already defined Body.Damage variable when it was defined at Body creation.
Any ideas why that happens? :S


local hp = ply:GetMaxHealth(), ply:Health() + heal

Trying to set a variable with two values will confuse the tits out of Lua, and it’ll just set it as nil.

If you want it to set it as GetMaxHealth, or ply:Health() + heal if GetMaxHealth is nil, use:


local hp = ply:GetMaxHealth() or ply:Health() + heal

If you want it to set whichever is lower, use:


local hp = math.min( ply:GetMaxHealth(), ply:Health() + heal 

You are calling serverside function Entity:SetHealth() on clientside.

But the script itself is shared.
How would I tell it to run the function serverside?

[lua]
if SERVER then
–Put that hook inside of one of these.
end
[/lua]

Oh, right. How stupid of me. Thank you <3
EDIT: Um, okay. I tried putting the hook inside that check, no workie. I also tried to just put SetHealth() stuff in the SERVER check, still no workie. .-.

LocalPlayer doesn’t exist serverside, you’ll need to modify the code to detect whichever player initiated the press. “KeyPress” returns a player and a key, so you can modify the code to detect these.

[lua]
hook.Add(“KeyPress”, “deathRagdollUse”, function( ply, key )
if key == IN_USE then
– etc
[/lua]

Thanks, man! I got everything working now.

Okay, now I would like it to call the function when you hold the keys down. How would I do that?
in think hook, I have no idea how could I find the player out. LocalPlayer() obviously wont work.
EDIT: Derp, figured it out from other scripts.


for k, v in pairs(player.GetAll()) do
*stuff*
end

in the “Think” hook.

Maybe KeyRelease instead of KeyPress?

[editline]8th June 2013[/editline]

nvm