So I'm trying to make a program in which involves me finding out whether or not a function inside a table should be called as a method, or as a regular function variable. I know the differences between these different formats, but I have yet to figure out whether or not you can tell with code.
For example:
local Methods = {} function Methods:Test1() print'Method 1 fired' end function Methods:Test2() print'Method 2 fired' end function Methods.Test3() print'Regular function fired' end -- Default attempt, but this will print all function values -- instead of differentiating between methods and regular -- functions. (I want to only print methods) for i,v in pairs(Methods) do if type(v) == 'function' then print(i) end end
I tried messing around with the built-in 'self' variable in methods, but still couldn't make any use of it. Is it possible for Lua code to find out whether or not a function should be called as a method?
EDIT:
I know how to call methods, I just don't know how to make code figure out whether a function in a table should be called as a method or not (assuming that it is indeed a method)
No, there's not:
Methods are just sugar. See this question for more details.
In brief:
obj:method(x, y) -- is equivalent to obj.method(obj, x, y)
and
function obj:method(x, y) -- (body) end -- is equivalent to function obj.method(self, x, y) -- (body) end
What this means is that a method is exactly the same thing as a function; there's just a little "convenience" added in.
You can inspect (to an extent) functions source using string.dump
. It looks like if you use the :
definition, it will insert an argument called self
automatically.
However, it's possible that the method was defined without using :
syntax and gave another argument to the first "self" argument.
e.g.,
workspace.Destroy
(note the .
) can't really be told apart from
function eliminate(p) return p:Destroy() end
since they both behave exactly the same.