In this question I would like to understand the reason for the failure of one of the functions that I will provide below.
The problematic code gives the error “attempt to perform arithmetic (mul) on number and nil” when the player exits the game
Note: the data table module.data sets data[userId] = nil when the player exits accordingly
First option (gives an error):
coroutine.wrap(function()
while true do
task.wait(1)
for _, player_data in pairs(require(ServerScriptService:WaitForChild("PlayerManager"):WaitForChild("DataStorage")).data) do
player_data["Coins"] += 1*player_data["CoinsMultiplier"] math.floor(player_data["Coins"])
end
end
end)()
Second option (does not give an error):
coroutine.wrap(function()
while true do
task.wait(1)
for _, player in pairs(game:GetService("Players"):GetChildren()) do
local data = require(ServerScriptService:WaitForChild("PlayerManager"):WaitForChild("DataStorage")).data[player.UserId]
if data then
data["Coins"] += 1*data["CoinsMultiplier"] math.floor(data["Coins"])
end
end
end
end)()
I also changed ipairs and pairs in both functions. But in the first version the error occurs with pairs, which is probably due to the difference between ipairs and pairs, but nevertheless, the second function (working) works with ipairs and pairs
The table itself with the player’s data may look something like this:
data = {
["Coins"] = 100;
["Skins"] = "0.1.5.4.2.";
["HasSword"] = true;
}