Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[SOLVED] How to dynamically access object properties ? i.e : myObj[‘aProp’] instead of myObj.aProp

edited January 6 in Questions Posts: 17

Hi all,
I created a generic class to display data tables but it won’t work if I feed it with classes instances instead of generic objects ({ like = « this »})

I wondered if it was possible to access a class instance property the same way we do it for generic objects. Unfortunately, the following code wont work :

Car = class()

function Car:init(model) 
  self.model = model
end

F = Car(‘Ford’)

F[‘model’] - - won’t return anything 

Do you guys know any workaround for this ?

Comments

  • dave1707dave1707 Mod
    edited January 6 Posts: 7,432

    @threads Try this one. The first one I posted wasn’t what you wanted. Your function B:init(model) should be Car:init(model).

    Using double quote

    function setup()
        F = Car("Ford")
        print(F["model"])
    end
    
    Car = class()
    
    function Car:init(model) 
      self.model = model
    end
    

    Using single quote

    function setup()
        F = Car('Ford')
        print(F['model'])
    end
    
    Car = class()
    
    function Car:init(model) 
      self.model = model
    end
    
  • edited January 6 Posts: 17
    @dave1707 No sorry that B:init was a typo in my example, it doesn’t work, you can’t call a property like this I guess
  • dave1707dave1707 Mod
    Posts: 7,432

    @threads Did you look at the last example. That looks like what you want and it works.

  • Posts: 17

    That’s weird because the following code doesn’t work for me :

     train = new Train(category, number, from, to, arrTime, depTime)
          print(train["category"])  - - FAILS
    
    
    function Train:init(category, number, from, to, arrTime, depTime)
    
      self.category = category
      self.number = number
      self.from = from
      self.to = to
      self.arrTime = arrTime
      self.depTime = depTime 
    
      ...  - - other stuff here  
    end 
    

    I’m not in the setup function though, but I can’t do it there

  • Posts: 17

    Oh my, it’s the « new » keyword : it doesn’t pop an error but it isn’t required and fails to build the object properly !

    Sorry, false alarm

    Thanks for your help @dave1707 !!!

  • dave1707dave1707 Mod
    Posts: 7,432

    @threads No problem, that’s what I’m here for. You learned something and that’s always a good thing.

Sign In or Register to comment.