Search code examples
oopluaprototype

Prototypes(OOP) - Can I Have Parameters in Object Functions?


Thanks for reading this post.

I'm working with Lua object prototypes as described by lua.org and tutorialspoint. However, I'm having some problems working with parameters passed to an object's function. Most likely, I am failing to understand some aspect of objects in Lua.

What I want is a function that lets me call upon any value stored in the object at the specified key.

something like:

function Class:getValue(key)
   print(self.key)
end

But this prints nil if I attempt object:getValue(key).

So far, I have the following code:

Gmenu = {zIndex=1,name="Menu",options=menuMain,optNum=3,xPos=0,yPos=0,width=30,height=90} 

function Gmenu:new(o,zIndex,name,options,xPos,yPos,width,height)
    o = o or {}
    setmetatable(o, self)
    self.__index=self
    self.zIndex=zIndex or 1
    self.name=name or "none"
    self.options=options or {}
    self.optNum=#options or 0   
    self.xPos=xPos or 0
    self.yPos=yPos or 0
    self.width=width or 0
    self.height=height or 0
    return o
end

function Gmenu:getParam(param) -- returns value at specified key in object
    if type(self.param) == table then
        printTable(self.param)
    else
        print(self.param)
    end
end

        xTest = Gmenu:new(nil,1,"Test Menu",menuBattle,50,50,100,120) 
        xTest:getParam(name)
        xTest:getParam(options)
        print(xTest.name)

The results I get from the last 3 lines of code are:

nil
nil
Test Menu

So a direct reference to the object's key yields the value, but self.name does not. Why is this the case?


Solution

  • In the body of :new function self is a class, and o is an instance being created.

    Assigning to self.zIndex modifies the field of class, this is not what you need.
    To initialize the instance field, you should use o.zIndex=zIndex or 1 instead.
    When accessing xTest.name, name field is absent in the instance xTest, so Lua fallbacks to reading the field name from its class, where it does exist.