Chaining methods is not working on this function

I am currently trying to chain methods on a module with metatables, but for some reason when returning self outside of the constructor, you can’t chain methods. Functions in question:

function module:myFunction(...)
    return self
end

function module:myFunction2(...)
    -- I can't chain methods on myFunction?
end

Just to clarify, the .new() constructor works perfectly fine.

You sure you’re doing it correctly? It seems to work fine for me

That’s exactly what I’m doing. Not sure why it’s not working.

what exactly isn’t working? Is there an error or is the method not doing what it’s supposed to do?

It’s just not doing what it’s supposed to. I mainly use the autocomplete menu, it does not show. I also tried it manually and it didn’t work either.

can u show me the script

(20 chars)

shortened version (still the same thing though):

local module = {}
module.__index = module

function module.new()
    local class = setmetatable({}, module)
    class.myString = "blah blah blah.."
    return class
end

function module:myFunction()
    return self -- can't chain methods with this??
end

function module:myEpicFunction()
    print(self.myString)
end

return module

What happens when you add the self-argument into the function, and change it to a ‘.’ instead of a ‘:’. This means when you call module:MyFunction(), it will actually call module.myFunction(self).

1 Like

This won’t change anything. You are still returning self, just getting it a different way.

1 Like

I’m not sure where you went wrong but this script is working for me.

local module = {}
module.__index = module

function module.new()
	local class = setmetatable({}, module)
	class.myString = "blah blah blah.."
	return class
end

function module:myFunction()
	return self -- can't chain methods with this??
end

function module:myEpicFunction()
	print(self.myString)
end

local m = module.new()
m:myFunction():myEpicFunction() --"blah blah blah.."

I assume it’s an issue with the way in which you require and/or use the module.

1 Like