Scripting Helpers is winding down operations and is now read-only. More info→
Log in to vote

Is there a way to find out if a function should be called as a method?

Asked by 8 years ago

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'

function Methods:Test2()
    print'Method 2 fired'

function Methods.Test3()
    print'Regular function fired'

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

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?


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)

1 answer

Log in to vote
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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)


function obj:method(x, y)
    -- (body)
-- is equivalent to
function obj.method(self, x, y)
    -- (body)

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.


workspace.Destroy (note the .) can't really be told apart from

function eliminate(p)
    return p:Destroy()

since they both behave exactly the same.


Answer this question