Defining/declaring not working

I’ve been having a little bit of struggle on this system I am making:

local DataStore = game:GetService("DataStoreService"):GetDataStore("Test1")

local hourWait = 12

game.Players.PlayerAdded:Connect(function(player)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "DailyReward"
	leaderstats.Parent = player
	
	local coins = Instance.new("IntValue")
	coins.Name = "Days"
	coins.Parent = leaderstats
	
	local timeSinceLastClaim
	
	local timeNow = os.time()

	local data

	pcall(function()
		local data = DataStore:GetAsync(player.UserId.."-FreeReward")
		print("Getting Data")
	end)
	
	print(data)
	
	if data ~= nil then

		timeSinceLastClaim = timeNow - data

		print("Time since last claim"..timeSinceLastClaim)
		
		game.ReplicatedStorage.ShowTimer:FireClient(player,timeSinceLastClaim)

		if (timeSinceLastClaim / 3600) >= hourWait then
			
			game.ReplicatedStorage.ShowDailyReward:FireClient(player)
			print("Find")
			game.ReplicatedStorage.ShowTimer:FireClient(player)
			print("Fireddd")
			local connection
			connection = game.ReplicatedStorage.ClaimReward.OnServerEvent:Connect(function(triggeringPlayer)
				if triggeringPlayer == player then
					DataStore:SetAsync(player.UserId.."-FreeReward",os.time())
					connection:Disconnect()
				end
			end)
		end
		
	else
		
		local timeNow = os.time()
		
		pcall(function()
		 	data = DataStore:GetAsync(player.UserId.."-FreeReward")
			print("Getting Data")
		end)
		
		timeSinceLastClaim = timeNow - data
		
		game.ReplicatedStorage.ShowDailyReward:FireClient(player)
		game.ReplicatedStorage.ShowTimer:FireClient(player,timeSinceLastClaim)
		print("Findddd")
		connection = game.ReplicatedStorage.ClaimReward.OnServerEvent:Connect(function(triggeringPlayer)
			if triggeringPlayer == player then
				player.ItemsPurchased.RequestEnabled.Value = false
				DataStore:SetAsync(player.UserId.."-FreeReward",os.time())
				connection:Disconnect()
			end
		end)
				
	end
	
end)

As you can see, I have defined “timeSinceLastClaim” at the top of the script. I then declared it below “if data ~= nil”. I did the same after the else statement and I keep getting this error:

attempt to perform arithmetic (sub) on number and nil

Everytime I get this message I get more and more frustrated as I am not getting this. Do you have a clue? Clearly I don’t.

This is your check to see if data is nil or not. Everything looks good here.

Then you used else for the if statement above, which means what’s inside it will run only when data IS nil.

and here is a line inside that else statement where you use data as if it actually has a value inside it. The problem is that it’s in the else section as well. I don’t know what you want it to do if data is nil,

but the problem here is that the line is in BOTH the if and else block of code.

Hope this helps!

1 Like