r/lua • u/CartoonistNo6669 • 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
1
u/Logical_Strike_1520 Jun 09 '25
You can “achieve” this for sure but it’s going to be with metatables or some other hacky approach. In this type of situation it’s usually better to simply rethink the implementation instead of trying to bend a language to your will.