What i want to achieve
I want make a table with of function (mostly used for datastores)
The issue
Currently, when the script runs, it errors with a “Attempt to call a nil value” error.
This
Script
local ds = game:GetService("DataStoreService")
local players = game:GetService("Players")
local exampledatastore = ds:GetDataStore("ExampleDataStore")
function GenerateKey(userid)
return string.format("Player_%s", tostring(userid))
end
local datastorefunctions = {
{
["Datastore"] = exampledatastore,
["OnJoin"] = function(plr, datastore)
local folder = Instance.new("Folder", plr)
folder.Name = "leaderstats"
local Wallet = Instance.new("IntValue", folder)
Wallet.Name = "Test"
local success, currentBal = pcall(function()
return datastore:GetAsync(GenerateKey(plr.UserId))
end)
if success then
print("Current Test Value:", currentBal)
Wallet.Value = currentBal
end
end,
["OnLeave"] = function(plr, datastore)
local success, err = pcall(function()
datastore:SetAsync(GenerateKey(plr.UserId), plr.leaderstats.Test.Value)
end)
if success then
print("Success")
end
end,
},
}
-- code for connecting all of the stuff
for _,data in ipairs(datastorefunctions) do
local datastore = data[1]
local joinFunction = data[2]
local leaveFunction = data[3]
players.PlayerAdded:Connect(joinFunction)
players.PlayerRemoving:Connect(function(plr)
leaveFunction(plr, datastore)
end)
end
game:BindToClose(function()
for _,player in pairs(players:GetPlayers()) do
for _,data in ipairs(datastorefunctions) do
local leaveFunction = data[3]
local datastore = data[1]
leaveFunction(player, datastore)
end
end
end)