lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Aug 3, 2011 at 15:06, Javier Guerra Giraldez <javier@guerrag.com> wrote:
> On Wed, Aug 3, 2011 at 3:01 PM, Hao Wu <wuhao.wise@gmail.com> wrote:
>> I am trying to do something like "this" pointer in c++.
>
> in most OO languages (C++ included), the 'this', 'self', 'me' pointer
> is just a parameter.  sometimes explicit (C, Python, Lua), sometimes
> invisible (C++, Lua).
>
> In fact, the 'OO style' functions in Lua is just a different syntax to
> make an invisible 'self' parameter, but it's totally equivalent to
> doing it explicitly.
>
> -- method definition
> function obj:meth(arg) .... end
> -- calling a method
> obj:meth(arg)
>
> is the same as:
>
> -- method definition
> function obj.meth(self,arg) ... end
> -- calling a method
> obj.meth(obj, arg)
>
> that's why you can use either:
>
> string.format (sss, v1, v2, ....)
> or
> sss:format (v1, v2, ...)
>
>
> tl;dr:  just add a 'self' first argument (can be named anything, but
> 'self' is more idiomatic in Lua than 'this')
>
> --
> Javier
>
>

Well, not totally equivalent:
function f()
  n = n + 1
  return foo
end

f():doSomething() --n is incremented once
f().doSomething(f()) --n is incremented twice

but that's a bit silly to do anyway. :)

-- 
Sent from my toaster.