Is there a different between these 2 lines of code?

This probably seems like a stupid question, but is there any difference between these 2 lines of code?

I created a quick and simple script for a time played leaderboard that goes up by 1 for every second the player is in the game.

game.Players.PlayerAdded:Connect(function(player)
	local playerStats = Instance.new("Folder")
	playerStats.Parent = player
	playerStats.Name = "leaderstats"
	
	local playtime = Instance.new("IntValue")
	playtime.Parent = playerStats
	playtime.Value = 0
	
	local function addTime()
		while true do
			--playtime.Value = playtime.Value + 1
			playtime.Value += 1
			task.wait(1)
		end
	end
	addTime()
end)

Inside of the while loop, there are 2 lines of code.

playtime.Value = playtime.Value + 1
playtime.Value += 1

I was curious, is there any difference between these 2? are there situations where you would use 1 over the other? I know they work exactly the same, but i was wondering if one is better to use than the other. Thank you!

2 Likes

They do the exact same thing. But most people use playtime.Value += 1 because it looks cleaner

2 Likes

Alright, thats what i was thinking. Are there any situations where you would use one over the other?

To add, you should utilize more of these operators as it makes your life easier, like for example:

local test = 1
test += 1 -- addition
test -= 1 -- subtraction
test /= 2 -- division
test *= 2 -- multiplication
test ^= 2 -- exponential
2 Likes

I appreciate the help guys. I was just wondering while playing around with datastores and leaderstats :+1:

Personal preference, but maybe if everyone uses +=1 to add in the codebase you would want to use that too so to keep code consistency

1 Like

yeah i can tell lol

playtime.Value += 1

looks a lot more readable and simpler than

playtime.Value = playtime.Value + 1
1 Like

Compound assignment also has a slight performance boost because it only evaluates the assignee once. So in addition to being more concise and easier to type, it just runs better. There’s genuinely no reason why someone would purposely not use it

In terms of Roblox, this also means only evaluating the instance hierarchy once, doing something like NumberValue.Value += 1 will only evaluate the pathing for .Value once which can be a big deal if you’re writing to it thousands of times a second

Additional proof because I know someone will ask:

2 Likes

This is very in-depth, you are the new solution lol, thank you.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.