Trying to run a function from a table errors

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)

You have a dictionary but try to get values as if it was a table, if you want the OnLeave function, you write data.OnLeave in your case, not data[3]

1 Like