Assignment is the means of changing a value in a variable, or a table.
local var = 'not a variable'
var = 'variable'
print(var)
expected output: variable
You can also take multiple variables and change their values in one line of code with a system called multiple assignment, like this:
local a
local b
a, b = 5, 7 --woah no way
print(a + b)
expected output: 12
When multiple assignment occurs however, Lua will often evaluate the values first before assignment occurs, which means you can swap values like this:
local foo = 'foo'
local bar = 'bar'
foo, bar = bar, foo --swap foo for bar
print(foo, bar)
expected output: bar foo
Multiple assignment will also give a variable the value of nil
if that variable isn't assigned a value, like here:
local a
local b
local c
a, b, c = 10, 20 --third value is missing, so the value is nil
print(a, b, c)
expected output: 10 20 nil
If there are too many values assigned to variables in multiple assignment as well, the script will just avoid those unnecessary values:
local a
local b
a, b = 1, 3, 5, 7, 9 --these last three values will be IGNORED
print(a, b)
expected output: 1 3
One thing to note about multiple assignment is that the order tends to change when an assignment is being evaluated too. Here's an example:
local a
a, a = 1, 5
print(a)
output: 1
But wait, why did this happen???
The order of assignment is not consistent, meaning that in a certain script like this one, the assignment order is actually right to left, and not left to right. This also tends to change with updates to Lua and other various tinkers.
Some people might use Assignment like the examples above, but programmers manipulate the power of assignment to do some wacky things with it.
A very good example is using multiple assignment to collect returns from functions by using function calls, like this:
foo, bar = myFunction()
Let's say that the function returns two values. foo would collect the first value, and bar would collect the second value. Then, we could utilize those values in our script for other things for all that we could care for. This is VERY useful if your script relies on functions to return values for systems and algorithms.
Assignment is a universal function that can be used to change values in a data structure.
Assignment can assign values to multiple variables.
Assignment has principles that it has to follow.
Assignment can do innumberable wonders, from collecting return values from a function, to swapping values between variables easily.