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.
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).
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.