How Can I Make Kill Only Once? Part 2

I’ve made some progress from previous post, however, I’m having difficulty with tables.

When I set it to nil, it still runs the command which I don’t understand. I haven’t done table in a while so if anyone can help me would be greatly appreciated.

function Kill(Player, Humanoid)
	local KillCurrency = math.random(5, 25)
	local playerTable = {}
	
	if Humanoid ~= nil --[[and game.Players:GetPlayerFromCharacter(Humanoid.Parent) ~= nil--]] then
		if Humanoid.Health <= 0 and Humanoid.Parent:FindFirstChild("HumanoidRootPart") then
			table.insert(playerTable, Player.Name)
			playerTable[Player] = true
			
			for i,v in pairs(playerTable) do
				if Player.Name == v and playerTable[Player] == true then
					Player.leaderstats:FindFirstChild("Kills").Value += 1
					Player.leaderstats:FindFirstChild("Credit").Value += KillCurrency
					
					playerTable[Player] = nil
					
					table.remove(playerTable, table.find(playerTable, Player))
				end
			end
		end
	end
end

You’re treating playerTable both as an array and a dictionary. It’s better to pick one method and stick with it. You’re also adding and removing the player in the same loop iteration.

Below uses a dictionary approach. Let me know if this works for you.

local playersTable = {}

local function addPlayerToTable(player)
    playersTable[player.Name] = true -- Adds player to table
end

local function removePlayerFromTable(player)
    playersTable[player.Name] = nil -- Removes player from table
end

function Kill(Player, Humanoid)
    local KillCurrency = math.random(5, 25)

    if Humanoid and Humanoid.Health <= 0 and Humanoid.Parent:FindFirstChild("HumanoidRootPart") then
        -- Check if player is already in the table
        if not playersTable[Player.Name] then
            -- Add player to the table
            addPlayerToTable(Player)

            -- Update player's stats
            Player.leaderstats:FindFirstChild("Kills").Value += 1
            Player.leaderstats:FindFirstChild("Credit").Value += KillCurrency

            -- Remove player from the table after updating stats
            removePlayerFromTable(Player)
        end
    end
end
2 Likes