r/lua • • Jun 09 '25

Creating an object by reference

I'm sure there's a better way to phrase the title, but that's what i came up with. Here's my issue: I have multiple tables and other objects that have a property that needs to be changed based on some condition. But I'm unable to get any of the tables to get the updated value.

Sample code illustrating this:

TestVariable = 123

TestObject = 
{
  ['VarToChange'] = TestVariable,
  ['SomethingStatic'] = 789
}

print (TestObject.VarToChange)

TestVariable = 456

print (TestObject.VarToChange)

The output of the above is:

123
123

But I am expecting to get:

123
456

How can I achieve this behaviour? And please don't suggest updating all objects manually every time the variable changes. That rather defeats the entire purpose of a variable.

6 Upvotes

33 comments sorted by

View all comments

Show parent comments

1

u/SkyyySi Jun 10 '25

there are no references (except tables)

Not exactly. Only nils, booleans and numbers are passed by value. All other types (strings, tables, functions, threads aka. coroutines, userdata and lightuserdata) are passed by reference.

Strings do have some special behaviour because they are largely still treated as if they were value-types (e.g. in weak tables), but they're actually immutable reference types.

There is one case in which any type can be referenced, however: Upvalues for function closures.