lua-users home
lua-l archive

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

Matthew Metnetsky wrote:
How does lua internally know that
the first argument might be the scope of the method (like python's self
argument) or not?

At the byte code level (at run time), it doesn't. It has no clue at all. It is all determined at compile/interpret time.

For the call side, when the source code

  object:method(arg1, arg2)

is compiled into byte codes, it is transformed to be:

  object.method(object, 7, 9)

The compiler sees the ':' in the original and performs the transformation (or behaves in a way that is as if the transformation occurred).

That is, the string 'method' is used as a key to index table (or userdatum) 'object'. The result will be called as a function and the table/userdatum 'object' is passed as the first argument, followed by 7 and 9.

When the method definition is compiled:

  function object:method(arg1, arg2)
     self.count = self.count + 1
     self.value = arg1 + arg2
     return self

the compiler knows, because of the ':' and because it is in a function definition, that a parameter whose name is self must be inserted before the parameters arg1 and arg2. So any references to self inside the definition are to this automatically created first parameter.

Note that if you were to use '.' instead of ':' in the method definition - by mistake, say - then any references to self would be to a global variable (or possibly a local in an outer scope) and not to the expected hidden first parameter.

As described in the manual, this is simply syntactic sugar to make a system that is not inherently object-oriented look like it is.