Captain Picard
Captain Picard

Reputation: 129

Using objects in Lua

So I am creating a system for Lua, so I can have classes and objects in it. I have the creation of objects down, the problem is creating constructors.

I have constructors like this:

a = MyClass:Create("Hello World!")

The create method has ... as its arguments which it passes on to the constructor method (OnStart). I can read the arguments just fine in the Create method but when OnStart is called the argument somehow ends up being nil instead of "Hello World!"

My code:

Object = { }

function Object:Create(...)
    local instance = { }
    setmetatable(instance, self)
    self.__index = self
    instance.Type = Object

    -- Now we can call the constructor.
    local arg = { ... }
    instance.OnStart(table.unpack(arg))

    return instance
end

function Object:OnStart(msg)
    print(msg)
end

test = Object:Create("Hello World!")
print(test:ToString())

Some how in here the msg argument ends up being nil...

Upvotes: 1

Views: 79

Answers (1)

Captain Picard
Captain Picard

Reputation: 129

It seems I have found out why it was not working, the slight detail that needs to be changed is one line 9. Instead of instance.OnStart it needs to be instance:OnStart.

Upvotes: 1

Related Questions