lua-users home
lua-l archive

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

On 5/7/2017 3:02 AM, nobody wrote:
(unless I fail at searching), the reference manual does not explicitly
state that metatables are "stored" by reference.  (I.e. `setmetatable`
doesn't copy the thing passed as metatable, but puts a reference to it
in a suitable location.)

The reference manual is very careful to be specific. If the table were copied, it would say that because that is different from how tables are used. It doesn't need to say that the table is not copied into internal storage because that is the normal case in any other use of tables. (The manual doesn't say that arithmetic never returns a string either. It doesn't, but saying so would raise the question of when it might.)

One could argue that this habit does make the reference manual harder to read for a language learner. But that is not the role of a reference manual. See Programming in Lua for one example (and likely the best example) of a language textbook that a learner should start with.

This lack of copying also follows from the way in which tables are treated as values. Since

    a = {}
    b = a = 1
    print(     -- prints "1"

is the way tables work in all other contexts, why would this be particularly different:

    mt = {}
    c = setmetatable({}, mt) = 1
    print(getmetatable(c).one) -- prints "1"

The fact that tables are "stored by reference" is just an implementation detail that makes the value semantics of tables practical to implement. This is similar to strings being internalized, which is also just an implementation detail that make their value semantics practical to implement.

Ross Berteig                     
Cheshire Engineering Corp. 
+1 626 303 1602