function arguments expected near ','

Viewed 5464

I have a class defined like so:

local MyClass = {
 _VERSION = 'MyClass 1.0.0'
}
MyClass.__index = MyClass

setmetatable(MyClass, {
    __call = function (cls, ...)
        return cls.new(...)
    end
})

function MyClass.new(prop1)
    local self = setmetatable({}, MyClass)
    self.prop1 = prop1
    return self
end

function MyClass:msg(txt)
    self.prop1 = txt
    print(self.prop1)
end

function MyClass:callFunc(func, ...)
    pcall(func, ...)
end

My client code may look like:

local inst = MyClass("value 1")
inst:msg("Hello world")
inst:callFunc(inst:msg, "Hello again")

When I run this client code, I get an error message

function arguments expected near ','

The code is completely reprodicible. You can easily check it here. Just copy paste and run it and you will get this error message. How can I fix it?

2 Answers

The problem is with using inst:msg in inst:callFunc(inst:msg, "Hello again"). The : syntax is only a "calling" convention (which is why it expects a function argument there), so can't be used to reference a method. You can simply replace it with inst.msg or MyClass.msg and get the same effect you expect without triggering the error.

I have a working solution. I got it just by chance. Here it is:

local MyClass = {
_VERSION = 'MyClass 1.0.0'
}
MyClass.__index = MyClass

setmetatable(MyClass, {
__call = function (cls, ...)
    return cls.new(...)
end
})

function MyClass.new(prop1)
    local self = setmetatable({}, MyClass)
    self.prop1 = prop1
    return self
end

function MyClass:msg(txt)
    if txt == nil then
        print(self.prop1)
    else
        self.prop1 = txt
        print("Two")
    end
end

function MyClass:callFunc(func, ...)
    pcall(func, ...)
end

-- client code

local inst = MyClass("value 1")
inst:callFunc(MyClass.msg, inst)

So, the main idea is to pass a function with dot notation as a first parameter and pass a class instance as a second parameter. Hope it will help someone.

Related