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

谁说我不能喝 提交于 2019-11-29 15:50:08

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

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.):

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!