"Attempt to perform arithmetic on a nil value", but how?

Hi!
I am setting up a simple Kill streak script, but it is giving out an error.

Here is the code:



PlayerKills = {}

function SetupPlayer(ply)
	PlayerKills[ply] = 0
end
hook.Add( "PlayerSpawn", "playerSpawn", SetupPlayer )

function GM:PlayerDeath( victim, weapon, killer )
	PlayerKills[victim] = 0
	if killer:IsPlayer( ) then

		PlayerKills[killer] = PlayerKills[killer] + 1

		if PlayerKills[killer] == 3 then

			killer:SetArmor(50)
			killer:SetHealth(100)

		elseif PlayerKills[killer] == 5 then

			killer:SetArmor(100)
			killer:SetHealth(100)

		end

	end

end


Error:



[ERROR] gamemodes/dmrng/gamemode/shared.lua:107: attempt to perform arithmetic on a nil value
  1. unknown - gamemodes/dmrng/gamemode/shared.lua:107


Any ideas on why it says it’s a nil value and how to fix it?

You haven’t set PlayerKills[killer] = 0, would be my best guess
You should probably set this stuff up in the InitialSpawn hook:
[lua]hook.Add( “PlayerInitialSpawn”, “SetupKillTable”, function( ply )
PlayerKills[ply] = 0 – or you could just copy/paste this line into the GM:PlayerInitialSpawn() function
end )[/lua]
This should ensure that you don’t get any table indexing errors for any players.

I usually store things player based on their SteamID.

Why not, instead of setting things up on spawn or initialspawn, just test to see if the values are initialized, if not then initialize them there?

[lua]PlayerKills = ( !PlayerKills ) && PlayerKills || { }; // Make it auto-refresh compatible; this can also be done different ways.

function GM:PlayerDeath( victim, weapon, killer )
// Don’t count non-player kills
if ( !IsValid( killer ) || !killer:IsPlayer( ) ) then return; end

local _steam = killer:SteamID( );

// Initialize...
if ( !PlayerKills[ _steam ] ) then PlayerKills[ _steam ] = 0; end

PlayerKills[ _steam ] = PlayerKills[ _steam ] + 1

if PlayerKills[ _steam ] == 3 then
	killer:SetArmor( 50 );
	killer:SetHealth( 100 );
elseif PlayerKills[ _steam ] == 5 then
	killer:SetArmor( 100 );
	killer:SetHealth( 100 );
end

end
[/lua]

I thought the PlayerSpawn cover the initial spawn as well, I was a fool, thanks for the help!

[editline]20th March 2014[/editline]

/thread