Defining Lua Methods as Initialization

In Lua, I can define functions in a table with something like

table = { myfunction = function(x) return x end }

I was wondering if I can create methods this way, instead of doing it like

function table:mymethod() ... end

I'm sure you can add methods this way, but I'm not sure about the name of this technique, and I can't find it in search of “lua” and “methods” or such.

I intend to pass the table to a function, for example myfunction({data= stuff, name = returnedName, ?method?init() = stuff}).

Unfortunately, I tried several combinations with a colon declaration, but none of them are valid syntax.

So ... does anyone here know?

+3
source share
1 answer

: table:method() - table.method(self), self.

tab={f=function(x)return x end }

tab:f(x) , tab.f(tab,x) , , tab x.

wiki wiki 16.

+5

Source: https://habr.com/ru/post/1786870/


All Articles