3

I'm new to Lua and I have work on project, I have an issue unterstanding what ":" I didn't found it on the manual for example how should interpret this piece of code :

res:template{
        main = 'functionform.html',
        functionjs = '_functionform.js',
        functionform = '_functionform.html'
    }
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
Engine
  • 5,360
  • 18
  • 84
  • 162

3 Answers3

6

The colon operatorPIL in Lua is a little syntatic sugar. It's used in object oriented Lua, to make a regular function call look more like a method call. What it does is pass the object as the self parameter when you call a function. Take this example:

a.myFunction(a, 'foo')

It's equivalent to:

a:myFunction('foo')

In your example, the method call is omiting the parentheses because its only argument is a tablePIL, so your function call without the colon operator would be somthing like:

res.template(res, {
        main = 'functionform.html',
        functionjs = '_functionform.js',
        functionform = '_functionform.html'
    })

So as you can see, this little syntatic sugar is pretty handy

William Barbosa
  • 4,936
  • 2
  • 19
  • 37
5

From the manual in section 2.5.8:

A function call in Lua has the following syntax:

functioncall ::= prefixexp args

In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type function, then this function is called with the given arguments. Otherwise, the prefixexp "call" metamethod is called, having as first parameter the value of prefixexp, followed by the original call arguments (see §2.8).

The form

functioncall ::= prefixexp `:´ Name args

can be used to call "methods". A call v:name(args) is syntactic sugar for v.name(v,args), except that v is evaluated only once.

So res:template{} is the same as res.template(res, {}).

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
3

The colon operator adds an additional 'hidden' parameter in method definition and argument in method call. (e.g. this / self)

http://www.lua.org/pil/16.html

So a call to your template function provides the hidden argument 'self' through which you can access the object on which the function is defined.

bash0r
  • 774
  • 6
  • 17