lua-users home
lua-l archive

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


On Wed, Dec 21, 2011 at 10:30 PM, Daurnimator <quae@daurnimator.com> wrote:
>> Patrick Rapin <toupie300@gmail.com> writes:
>> > My proposal is the following: provided it is possible, why not limit
>> > the metatable scope to the environment of the current function?
>> > Even better, I could imagine that the type metatables could be placed
>> > in the metatable of _ENV and manipulated from there.
>> > Type metatables are nearly unusable in a library, since the library
>> > author cannot assume that the custom metatable won't have side effects
>> > or conflicts in other libraries or user scripts.
>>
>> Soooo what are the details?  How does the compiler implement this?
>> How would it impact performance?

I had similar ideas in [1] for the same reasons.  It does not
necessarily require a change to the VM but could be implemented at
compile time or as a preprocessor (including Metalua).  For example,

  do
    local function __index(t, k) print('Indexing', t,k); return t[k] end
       --- note: t[k] must be "raw"-like, not causing recursion
    print(math.pi) --> Indexing table: 0x9c18370 pi 3.1415926535898
  end
  print(math.pi) --> 3.1415926535898

could be transformed to standard Lua:

  do
    local function __index(t, k) print('Indexing', t,k); return t[k] end
    print(__index(math,'pi'))
  end
  print(math.pi)

The above metamethod would apply to values of *all* types in the
lexical scope since, in general, types of values are not known at
compile time.  You may, however, test the 'type(t)' inside the
metamethod (executed at runtime), and perhaps LuaJIT tracing can avoid
the overhead in cases where the test is false.

Other variants of this idea may require VM changes.

[1] http://lua-users.org/lists/lua-l/2010-06/msg00515.html - "lexical
metamethods"