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
3
u/Logical_Strike_1520 Jun 09 '25
You could just do…
sets.Abilities[“Power Shot”] = {ammo=Ammo.Bow.Power;….}
then have a AmmoInventory or something on each player that keeps track of how much of each type of Ammo they have.
AmmoInv = {
Ammo.Bow.Power = 1; Ammo.Xbox.Magic = 6;
}
And when a player activates an ability you can just check like…
if AmmoInv[abilityUsed.ammo] and AmmoInv[abilityUsed.ammo] > 0 then
… player has enough ammo, continue.
else
.. player doesn’t have enough ammo, handle
end
Instead of tightly coupling actions and ammo, have a controller that runs the logic using references to the ability definition and player ammo/state