lua: check subject of a method -
obj = {} function obj:setname(name) print("obj: ", self) print("name: ", obj) end
i create object , assign method above. call way:
obj:setname("blabla")
the self identifier refers obj. problem function potentially accessed via
obj.setname("blabla")
in case, obj won't passed argument , "blabla" take place of self parameter instead of serving name. because : operator in function declaration shorthand/sugar syntax for
function obj.setname(self, name)
can somehow check if self subject/if function has been run colon? cannot told argcount nor can write obj in function directly because instantiated , function refered outside scope define it. idea check if self possesses member "setname"
function obj:setname(name) if ((type(self) ~= "table") or (self.setname == nil)) print("no subject passed") return end print("obj: ", self) print("name: ", obj) end
but that's not clean either.
edit: doing now:
local function checkmethodcaller() local caller = debug.getinfo(2) local selfvar, self = debug.getlocal(2, 1) assert(self[caller.name] == caller.func, [[try call function ]]..caller.name..[[ invalid subject, check correct operator (use : instead of .)]]) end function obj:setname(name) checkmethodcaller() print(self, name) end
you can assign metatable object , inside setname method check whether self's metatable appropriate:
obj = {} local objmt = {} setmetatable(obj, objmt) function obj:setname(name) if getmetatable(self) ~= objmt error("panic, wrong self!") -- or handle more gracefully if wish end self.name = name end
edit:
of course, if intentionally replaces or removes metatable, entirely break function.
Comments
Post a Comment