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:
01 | local Methods = { } |
02 |
03 | function Methods:Test 1 () |
04 | print 'Method 1 fired' |
05 | end |
06 |
07 | function Methods:Test 2 () |
08 | print 'Method 2 fired' |
09 | end |
10 |
11 | function Methods.Test 3 () |
12 | print 'Regular function fired' |
13 | end |
14 |
15 | -- Default attempt, but this will print all function values |
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:
1 | obj:method(x, y) |
2 | -- is equivalent to |
3 | obj.method(obj, x, y) |
and
1 | function obj:method(x, y) |
2 | -- (body) |
3 | end |
4 | -- is equivalent to |
5 | function obj.method(self, x, y) |
6 | -- (body) |
7 | 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
1 | function eliminate(p) |
2 | return p:Destroy() |
3 | end |
since they both behave exactly the same.