Can't understand the meaning of the sentence

Recently I started studying the different types of operators in scripting. I am currently learning about compound assignment. But then I found this sentence:

The operation in a compound assignment occurs once. For example, if an expression generates a random index in a table, Luau uses the same index for both the operation and the assignment."

I can understand the first sentence but the second is so confusing. Is the expression a compound assignment? Can someone further explain this sentence to me, thanks.

It means the operation in a compound assignment occurs once

Example:

local t = {5,10,15,20}
t[math.random(#t)]  += 1
-- Assume math.random returns 3
--> t = {5,10,16,20}

Here, math.random(#t) is only evaluated once even though if you were to write it out fully it would be:

local t = {5,10,15,20}
t[math.random(#t)] = t[math.random(#t)] + 1
-- Assume math.random returns 3
-- Assume the second math.random returns 2
--> t = {5,10,11,20}

Here math.random(#t) would be evaluated twice giving you unintended results

1 Like

Oh, so compound assignments are used to shorten scripts, make them more readable and to not get unintended results?

They are used for convenience.

-- Compound
local t = {5,10,15,20}
t[math.random(#t)]  += 1
-- Expanded
local t = {5,10,15,20}
local index = math.random(#t)
t[index] = t[index] + 1

These two are exactly the same. The first one is just more convenient to write out.

1 Like

Thanks for the help! Appreciate it…

1 Like

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