lua-users home
lua-l archive

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

I can add also that,because metatables are normal tables, they can also have their own metatables, so this would make sense:
to create a empty table whose metatable is a second empty table whose metatable is a third empty table whose metatable is nil.

And instead of the code:
  t = {1,2,3};  setmetatable(t, {4,5,6})
you can write directly and much more simply:
  t = {1,2,3}:{4,5,6}

Le lun. 5 nov. 2018 à 00:15, Philippe Verdy <> a écrit :

For assigning variables with external scopes, e.g. an table contains an inner table (which internally defines a table "b"), and the table "b", something like:
  x =  {[:b], {[:*b]={}}, b}[1]
* the scope of "b" is the outer table in which it is defined locally (but does not generate any key/value pair in the outer table in construction), but then it is assigned the reference to the innermost table.
* what you get from this _expression_ is a table x such that x[2] = {}, and x[1] = {x[2]}.
* there's NOTHING in the table x (or its metatable which is nil here) that still contains the name "b" used only during its construction.
Sorry I made several typos in this example sent too soon (missing brace and incorrect use of [] for what is not a key but a value, I meant:
  x =  { :b, { {::b={3,4,5} }, b } }[1]  
 note that the external scope is explicited by the two colons "::", we can imagine using three colons or more to count the enclosing scopes, or using ":*" to refer directly to the global scope (where the variable is set outside the table constructor itself, as a normal variable which makes things simpler (no need to isolate the "b" in a temporary enclosing table to restrict its scope, and then drop this temporary table by indexing it with "[1]").
  b = 1;
  x =  { { :*b = {3,4,5} }, b } 
and also changes the value in variable "b" by replacing it with the constructed value is accessible after the construction. So the value of variable "b" is no longer 1, but the innermost table {3,4,5},
and we have x[1][1] === b and x[2] === b