3

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?

RBerteig
  • 41,948
  • 7
  • 88
  • 128
viktorry
  • 167
  • 1
  • 6

1 Answers1

5

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.

RBerteig
  • 41,948
  • 7
  • 88
  • 128
jpjacobs
  • 9,359
  • 36
  • 45
  • Oh it works. ...there was I searching for a convoluted solution when it is that simple. Ahem. Thanks a lot! – viktorry Jan 21 '11 at 10:01
  • 2
    Just a comment - when making "methods", the first parameter is usually named 'self'. This is what the function tab:method() syntactic sugar does. If you want to call it through ':', create your function as such: tab = { f = function(self, x) return x end } and call as tab:f(x). – Michal Kottman Jan 21 '11 at 12:08