Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Lua methods as initialization

In the Lua language, I am able to define functions in a table with something such as

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

I wondered if I can created methods this way, instead of having to do it like

function table:mymethod() ... end

I am fairly sure it is possible to add methods this way, but I am unsure of the proper name of this technique, and I cannot find it looking for "lua" and "methods" or such.

My intention is to pass a table to a function such as myfunction({data= stuff, name = returnedName, ?method?init() = stuff}).

Unfortunately I have tried several combinations with the colon method declaration but none of them is valid syntax.

So...anyone here happens to know?

like image 912
viktorry Avatar asked Jul 26 '26 12:07

viktorry


1 Answers

Sure: table:method() is just syntactic sugar for table.method(self), but you have to take care of the self argument. If you do

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

then tab:f(x) won't work, as this actually is tab.f(tab,x) and thus will return tab instead of x.

You might take a look on the lua users wiki on object orientation or PiL chapter 16.

like image 166
jpjacobs Avatar answered Jul 28 '26 13:07

jpjacobs