Pointers in Lua
Lua supports references, allowing you to pass references to values and tables within your program.
We’ll show how references work in contrast to values with 2 functions: zeroval
and zeroref
. zeroval
has a number parameter, so arguments will be passed to it by value. zeroval
will get a copy of ival
distinct from the one in the calling function.
zeroref
in contrast takes a table parameter. In Lua, tables are always passed by reference. Assigning a value to a table field changes the value in the referenced table.
Here’s how we use these functions:
zeroval
doesn’t change the i
in the main chunk, but zeroref
does because it has a reference to the table containing the value.
When we run this program, we get:
In Lua, tables are the primary mechanism for creating references. While Lua doesn’t have explicit pointers like some other languages, tables provide a way to achieve similar functionality in many cases.
When you pass a table to a function or assign it to another variable, you’re working with a reference to that table. This allows you to modify the contents of the table from different parts of your code.
Remember that in Lua, only tables and functions are passed by reference. All other types (numbers, strings, booleans, etc.) are passed by value.