Vitaly
Vitaly

Reputation: 4498

Method declaration in Lua

Is there any difference between these two types of declarations performance-wise?

local object = newObject()

function object:method(params)
end

local object:method = function(params)
end

Upvotes: 3

Views: 1173

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473437

Yes, there is a difference. The second one doesn't compile. So it has zero performance ;)

A "method declaration" is just syntactical sugar in Lua. These are identical:

function object.func(self, param)
end

function object:func(param)
end

But that sugar only works if you are naming the function as part of the function declaration.

The ':' syntax for accessing "methods" in Lua only works for accessing functions that are stored in a table, named by a string key. You cannot use this syntax to set the value of a table.

Or, to put it another way, there is no other way to do this:

function object:func(param)
end

without explicitly specifying a 'self' parameter as the first parameter.

Upvotes: 6

Related Questions