Lua: colon notation, 'self' and function definition vs. call

我们两清 提交于 2019-12-05 12:47:50

Your assumptions are all correct.

Assumption 1 from the manual:

The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement

 function t.a.b.c:f (params) body end

is syntactic sugar for

 t.a.b.c.f = function (self, params) body end

Assumption 2 from the manual:

A call v:name(args) is syntactic sugar for v.name(v,args), except that v is evaluated only once.

Assumption 3 doesn't have a direct manual section since that's just normal function call syntax.

Here's the thing though. self is just the auto-magic name given in the syntax sugar used as part of the colon assignment. It isn't a necessary name. The first argument is the first argument whatever the name happens to be.

So in your example:

function string.PatternSafe( str )
    return ( str:gsub( ".", pattern_escape_replacements ) );
end

the first argument is str so when the function is called as char:PatternSafe() is de-sugars (via assumption 2) to char.PatternSafe(char) which is just passing char to the function as the first argument (which, as I already said, is str).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!