Lua: References
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
One potentially confusing aspect of some Lua types is the fact that they are referenced, instead of being bound to a single name. The of Lua's 8 datatypes, the following objects are reference-based:
- Tables
- Functions
- Userdata
- Threads
This script illustrates how references work:
a = { }
b = { }
print(a == b) -- false
Both tables are empty, so why aren't they considered the same? In a value-based system, they would be; however since references are being used, they are being compared based on their memory addresses rather than their contents. See:
print(a, b) -- 016C38C8, 016C67D0 (exact addresses will vary, but will still be unequal)
There are advantages and disadvantages to using a reference system: different variables can be set to point to the same data, but if you want a straight-up copy of the data, you have to do it yourself. References can also speed up certain operations, for example, comparing if strings are equal or not equal; since Lua hashes strings, all it has to do is check whether or not the hashes of the two strings match, instead of going through character-by-character. Of course, less-than or greater-than comparisons will still require a run-through.
Similarly to the first example, you just may want to check if a table is empty. You can't use references for this, obviously, but you have two other options:
print(#a == 0) -- true
print(not next(a)) -- true
Note that the length operator will only be reliable when tables are used as arrays conforming to Lua's definition of an array (1-based contiguous positive indices); any other types of keys will be ignored. However, not next(a) will work regardless.