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.

function zeroval(ival)
    ival = 0
end

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.

function zeroref(itbl)
    itbl.value = 0
end

Here’s how we use these functions:

local i = 1
print("initial:", i)

zeroval(i)
print("zeroval:", i)

local iref = {value = i}
zeroref(iref)
print("zeroref:", iref.value)

-- Tables can be printed too.
print("reference:", tostring(iref))

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:

$ lua pointers.lua
initial: 1
zeroval: 1
zeroref: 0
reference: table: 0x55f748212460

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.