Tables are references

The last thing to know about tables before moving on to the next section is that they are stored by reference, not value! This is very important: integers and other primitive types are assigned by value, tables are assigned by reference. What does this mean?

If you assign one variable to another variable by value, each variable has its own copy. This means you can edit both variables independently. Here is an example:

x = 10 -- y assigned 10 by value
y = x -- y assigned the value of x (10) by value

x = 15 -- x assigned 15 by value

print (x) -- 15
print (y) -- 10

When you assigned a variable by reference, however, multiple variables might hold the same reference. If you assign the same reference to multiple variables, changing one variable will change the data referenced by all variables. This can cause subtle bugs to appear in your code. The following code demonstrates this:

a = {} -- a is assigned a table reference
b = a -- b references the same table as x

b.x = 10 -- also creates a.x, a and b reference the same table
a.y = 20 -- also creates b.y, a and b reference the same table
a.x = 30 -- also changes b.x, a and b reference the same table

-- Even tough we assigned different variables to a.x and b.x
-- because the variables reference the same table, they should
-- both have the same value
print ("a.x: " .. a.x) -- prints a.x: 30
print ("b.x: " .. b.x) -- print b.x: 30

print ("a.y: " .. a.y) -- printx a.y: 20
print ("b.y: " .. b.y) -- prints b.y: 20

a = nil -- a no longer references the table
b = nil -- nothing references the table after this

Take note of the last two lines. Both variables a and b are set to nil. When a table is not referenced by any variable, it becomes eligible for garbage collection. Garbage collection is the mechanism in Lua by which memory is freed, so that it can be re-used later. Once a table is no longer needed, all references to that table should be made nil.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.137.7