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

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

Asked by 9 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:

01local Methods = {}
02 
03function Methods:Test1()
04    print'Method 1 fired'
05end
06 
07function Methods:Test2()
08    print'Method 2 fired'
09end
10 
11function Methods.Test3()
12    print'Regular function fired'
13end
14 
15-- Default attempt, but this will print all function values
View all 22 lines...

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)

1 answer

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

No, there's not:

Methods are just sugar. See this question for more details.

In brief:

1obj:method(x, y)
2-- is equivalent to
3obj.method(obj, x, y)

and

1function obj:method(x, y)
2    -- (body)
3end
4-- is equivalent to
5function obj.method(self, x, y)
6    -- (body)
7end

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

1function eliminate(p)
2    return p:Destroy()
3end

since they both behave exactly the same.

Ad

Answer this question