obj = {}
function obj:setName(name)
print("obj: ", self)
print("name: ", obj)
end
I create an object and assign a method like above. Now I call it this way:
obj:setName("blabla")
The self identifier then refers to obj. My problem is that the function could also potentially be accessed via
obj.setName("blabla")
In this case, obj won't be passed as an argument and "blabla" will take the place of the self parameter instead of serving the name. That is because the : operator in the function declaration is only a shorthand/sugar syntax for
function obj.setName(self, name)
Can I somehow properly check if self really is the subject/if the function has been run by colon? It cannot be told from argCount nor can I write obj in the function directly because it will be instantiated and the function is refered to from outside the scope where I define it. My only idea is to check if self possesses a member "setName"
function obj:setName(name)
if ((type(self) ~= "table") or (self.setName == nil)) then
print("no subject passed")
return
end
print("obj: ", self)
print("name: ", obj)
end
but that's not clean either.
edit: Doing it like this now:
local function checkMethodCaller()
local caller = debug.getinfo(2)
local selfVar, self = debug.getlocal(2, 1)
assert(self[caller.name] == caller.func, [[try to call function ]]..caller.name..[[ with invalid subject, check for correct operator (use : instead of .)]])
end
function obj:setName(name)
checkMethodCaller()
print(self, name)
end