0
votes

In my example, I am creating a class Person and setting a default value for the member "Name". I have a constructor, and a function called sayHi(). Whenever I try to call that function I get an error:

lua: test.lua:22: attempt to call a nil value (method 'sayHi')
stack traceback:
        test.lua:22: in main chunk
        [C]: in ?

So from what I understand I am creating a new table, setting the table's metatable (setmetatable) to the Person class, and then returning that table, which means I should be able to use its sayHi() function, but I am getting a nil value.

Person = {}

Person.Name = "No name inputted"

function Person:new(name)
    local o = {}
    setmetatable(o,self)
    self._index = self
    return o
    
end

function Person:sayHi()
    print(self.Name .. " says hi")
end


firstPerson = Person:new("Michael")
secondPerson = Person:new("Julian")

print(firstPerson.Name)
secondPerson:sayHi()


1

1 Answers

2
votes

The correct property name on metatables is __index (two leading underscores). You're assigning to _index (one leading underscore).