Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass `self` implicitly to function when calling with square brakets?

Tags:

lua

If you call a function like this:

some_table:method (a, b)

...then the function will receive some_table as its first argument, and many functions dub this self (or use a notation function Some_Class:method (a, b) where it's done for them), and assume it is an object that has this function as a method.

However, if the name of the method to be called isn't known at implementation time, you need to use square brackets to access a function, like this:

some_table [method_name] (a, b)

...and in that case the respective method won't get some_table as self. Of course we can pass it manually, like this:

some_table [method_name] (method_name, a, b)

But that's a bit inconvenient (especially if some_table is actually an expression like some_other_table [member].children [4]:getHelperTable().helper (a contrived example). Is there some sort of syntactic sugar or a magic trick to pass self implicitly in this case?

like image 248
Septagram Avatar asked Oct 28 '25 05:10

Septagram


1 Answers

Nope.

The only syntactic sugar of this form is foo:bar(...) which translates into foo.bar(foo, ...) - anything else you just have to provide the first argument manually.

You could of course just write a wrapper function:

function selfcall(obj, method, ...)
    obj[method](obj, ...)
end

Then your example becomes something like...

selfcall(some_other_table[member].children[4]:getHelperTable().helper,
         method_name)

Of course, another option is to just use a local to store the expression:

local foo = some_other_table[member].children[4]:getHelperTable().helper
foo[method_name](foo)
like image 111
Amber Avatar answered Oct 31 '25 10:10

Amber