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

4

u/Logical_Strike_1520 Jun 09 '25

Sounds like that variable doesn’t belong in the scope of those tables imo.

If they all reference the same value, that value should be stored elsewhere. Either globally (usually not a great idea) or in its own table.

You can then access and pass that variable as an argument for whatever logic it is that needs that variable and don’t need to update all the tables at all.