Lua中的方法声明(Method declaration in Lua)

这两种类型的声明在性能方面有没有区别?

local object = newObject() function object:method(params) end local object:method = function(params) end

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

最满意答案

是,有一点不同。 第二个不编译。 所以它的性能为零;)

“方法声明”只是Lua中的语法糖。 这些是相同的:

function object.func(self, param) end function object:func(param) end

但是只有在将函数命名为函数声明的一部分时,该糖有效。

用于访问Lua中的“方法”的':'语法仅适用于访问存储在表中的函数,这些函数由字符串键命名。 您不能使用此语法来设置表的值。

或者换句话说,没有其他办法可以做到这一点:

function object:func(param) end

而不显式指定'self'参数作为第一个参数。

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.

更多推荐