Confusion of using “.” notation with __index and namespace in Lua

前端 未结 1 1651
误落风尘
误落风尘 2020-12-21 17:40

I am confused of the following two syntaxes using \".\"

  1. From what I understand, __index is called when a key doesn\'t exist in a table but exis

相关标签:
1条回答
  • 2020-12-21 18:16

    So why does the list table call __index and then assign itself to list.__index?

    Nowhere in your code does the list table call __index. The assignment part however is a common Lua idiom (aka. hack) to save some memory. Conceptually there are 4 different kinds of tables involved:

    1. list objects (the tables created via {length=0} in your code)
    2. a metatable (containing an __index field) that modifies the behavior of list objects when you try to access non-existing fields in the object
    3. the list class, which holds all the methods for list objects (like the push method), and also serves as a constructor for list objects
    4. a metatable (containing a __call field) for the list class, so that you can call the list table as if it were a function

      list objects separate metatable and index table

    As metatable fields always start with two underscores (__), and normal methods usually don't, you can put metatable fields and normal methods side by side into a single table without conflict. And this is what happened here. The list class table also serves as metatable for list objects. So using this trick you can save the memory you would normally need for the separate metatable (the size in bytes for Lua 5.2 on an x86-64 Linux is shown in square brackets in the table title bars, btw.):

    list objects with merged metatable and index table

    Does Window.mt simply create a table?

    No, {} creates a table. However, this new table is saved under key "mt" in the Window table, probably to give users of this Window "class" direct access to the metatable that is used for window objects. Given only the code you showed this is not strictly necessary, and you could have used a local variable instead.

    Why do we need Window = {} as a namespace here?

    In principle, you could store Window.mt, Window.new, and Window.prototype separately, but that would get cumbersome if you have multiple "classes" like Window. This way you can avoid name clashes, and using the Window "class" looks nicer.

    Another reason might be that require can only return a single value from a module definition, and if you want to export multiple values (like new, mt, and prototype) from a module, you need a table to wrap them together (or use global variables, but that is considered bad style).

    0 讨论(0)
提交回复
热议问题