lua

Construct array with object reference


Not sure if I'm phrasing this correctly, but I have the following test code:

TestVariable = 123

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

print (TestObject.VarToChange)

TestVariable = 456

print (TestObject.VarToChange)

The output of which is:

123
123

I was expecting that changing the TestVariable value that it would also update the array, but that does not appear to be the case. In other words, I was expecting the output to be this:

123
456

Is there a way to accomplish this in lua? How can that be done?


Solution

  • You are not updating your table. but a variable, as far as the table is concerned that variable no longer exist where you are trying to modify it. what would work is

    TestObject.VarToChange = TestVariable
    

    so to rewrite you should test the following

    TestVariable = 123
    
    TestObject = 
    {
      ['VarToChange'] = TestVariable,
      ['SomethingStatic'] = 789
    }
    
    print (TestObject.VarToChange)
    
    TestVariable = 456
    TestObject.VarToChange = TestVariable 
    print (TestObject.VarToChange)
    

    To use metamethod to achieve this based on your follow up comment.
    Note: Code can be improved to be cleaner.

    TestVariable = 123
    
    TestObject = 
    {
      ['VarToChange'] = TestVariable,
      ['SomethingStatic'] = 789
    }
    local metatable = {
      __index = function(table, key)
        if key == "VarToChange"  then
          data.VarToChange = data.VarToChange
        end
        return data[key]
      end,
    
      __newindex = function(table, key, value)
        data[key] = value
        if key == "VarToChange" then
          data.VarToChange = data.VarToChange
        end
      end
    }
    
    setmetatable(TestObject, metatable)
    
    
    
    print(TestObject.VarToChange)
    
    
    TestObject.VarToChange = 456
    print(TestObject.VarToChange)