Invalid argument #3 (string expected, got nil)

hello everyone, I am having an issue with my code and it really stumped me. For line 33 or the " Value3.Value = data[‘Melee’]" it says (as error)

invalid argument #3 (string expected, got nil)

which really got me confused because it works for line 31 and 32. Any help on this.

Script (data store)

local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")

local function onPlayerJoin(player)

	local stats = Instance.new("Folder", player)
	stats.Name = 'leaderstats'

	local Loadouts = Instance.new("Folder") 
	Loadouts.Name = "Loadouts" 
	Loadouts.Parent = player 
	local Value1 = Instance.new("StringValue") 
	Value1.Name = "Primary" 
	Value1.Parent = Loadouts 
	Value1.Value = "M4A1" 

	local Value2 = Instance.new("StringValue") 
	Value2.Name = "Secondary" 
	Value2.Parent = Loadouts
	Value2.Value = "Deagle" 
	local Value3 = Instance.new("StringValue") 
	Value3.Name = "Melee" 
	Value3.Parent = Loadouts 
	Value3.Value = "CombatKnife" 	
	local playerUserId = "Player_" .. player.UserId  

	local data = playerData:GetAsync(playerUserId)

	if data then
		Value1.Value = data['Primary']
		Value2.Value = data['Secondary']
		Value3.Value = data['Melee']
	else
		Value1.Value = "M4A1"
		Value2.Value = "Deagle"
		Value3.Value = "CombatKnife"
	end
end



local function create_table(player)
	local player_stats = {}
	for _, stat in pairs(player.Loadouts:GetChildren()) do
		player_stats[stat.Name] = stat.Value
	end
	return player_stats
end



local function onPlayerExit(player) 
	if player.Loadouts.Primary.Value == "SG552" then 
		player.Loadouts.Primary.Value = "M4A1"
	end
	local player_stats = create_table(player)
	local success, err = pcall(function()
	local playerUserId = "Player_" .. player.UserId
		playerData:SetAsync(playerUserId, player_stats)
	end)

	if not success then
		warn('Could not save data!')
	end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)
1 Like

It’s probably because there is nothing stored in data['Melee']. You’re only checking if data exists, not if there are actual values stored. You can add a fallback value if it returns nil:

Value1.Value = data['Primary'] or "M4A1"
Value2.Value = data['Secondary'] or "Deagle"
Value3.Value = data['Melee'] or "CombatKnife"
3 Likes