lua-users home
lua-l archive

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


Luiz Henrique de Figueiredo writes:
> > I have a new patch that allows table constructs to enclose a scope
> > so that variables used inside the table have special meaning.
> 
> Interesting but strange: it uses a run-time feature (the __scope metamethod)
> to implement name resolution that only occurs once, at table creation.

The same can be said without this patch, but replace "(the __scope metamethod)"
with "(the environment table)".

> Also, strictly speaking, you could argue that the __newindex metamethod
> could work just as well in that case. There'd be no need for a separate
> metamethod; just extend its semantics to table creation.

Yes, the __index metamethod, that is.  The reason I opted for a new metamethod
was for the much lower potential to break existing programs, and it makes it
easier to turn off the table scope resolution or have it be independent of
method/field access.  But that might be reasonable.

A similar mechanism based on __newindex might allow trapping of assignment of
identical keys or nil to a table:

  t = multimap {a=1, a=2, b=3, nil}

Otherwise, those keys are lost, even though they exist in the byte code:

  $ echo 't={a=1,a=1,b=3,nil}' | luac -p -l -
  main <stdin:0,0> (8 instructions, 32 bytes at 0x680dd0)
  0+ params, 2 slots, 0 upvalues, 0 locals, 5 constants, 0 functions
          1       [1]     NEWTABLE        0 1 3
          2       [1]     SETTABLE        0 -2 -3 ; "a" 1
          3       [1]     SETTABLE        0 -2 -3 ; "a" 1
          4       [1]     SETTABLE        0 -4 -5 ; "b" 3
          5       [1]     LOADNIL         1 1
          6       [1]     SETLIST         0 1 1   ; 1
          7       [1]     SETGLOBAL       0 -1    ; t
          8       [1]     RETURN          0 1