I made some code to check how many players have each type of an item. I was doing it in a module but decided to do it in the same script. the problem is that it runs properly once, but after the first time returns the same exact values in the table. Here’s an example:
I currently have 2 tools in my game, a lighter and a flashlight. If the table prints in the output it should look like this.
– if 5 players have a flashlight and 2 players have a lighter:
{
[“Flashlight”] = 5,
[“Lighter”] = 2,
}
The next time it runs, if one less person has a lighter, it should look like this, right?
{
[“Flashlight”] = 5,
[“Lighter”] = 1,
}
Nope. It prints the first table every single time. I know this because I ran it, deleted a tool from my inventory, ran it again, and then it gave me the same table. The function creates and returns a new table every time, so I don’t know why this is happening. Here’s the code.
local function newItem()
local function itemCheck()
local toolTable = {
["Flashlight"] = 0;
["Lighter"] = 0;
}
for _, player:Player in ipairs(game.Players:GetChildren()) do
for key, v in toolTable do
if player.Backpack:FindFirstChild(key) or player.Character:FindFirstChild(key) then
toolTable[key] += 1
end
end
end
return toolTable
end
local playersWithTool = itemCheck()
print(playersWithTool)
end
newItem()
I actually call this function every time a new room spawns, but for the example im just gonna leave it at this. Im using this to only spawn tools that not everyone has, or only items (ie batteries) that someone needs, so I kinda need to fix this. Forgive me if the solution is simple.