问题描述
我早些时候问过Lua为什么没有找到我的元表方法,并被告知通过将__index设置为我的元表,它可以解决问题,所以我假设调用时是一种方法在搜索按元表中的索引进行操作,但是现在遇到了一个问题,我需要在我的元表上使用索引括弧[和],因此分配了__index以便从其中的表返回索引,如何解决使用方法和使用索引括号的功能需求
I asked earlier why my methods for a metatable weren't being located by Lua, and was told that by setting __index to my metatable, that it would resolve the issue, so I assumed that a method when called was searching by index in the metatable, but I've ran into an issue now that I need to use indexing brackets [ and ] on my metatable, so __indexis assigned to return an index from a table inside of it, how do I resolve the functionality needs of both using methods, and use of indexing brackets
我写了一个表明问题的最小示例:
I wrote a minimal example indicating the problem:
TestMetatable = {DataTable = {}} TestMetatable.__index = TestMetatable function TestMetatable.new() local Tmp = {} setmetatable(Tmp,TestMetatable) Tmp.DataTable = {1} return Tmp end function TestMetatable:TestMethod() print("Ran Successfully") end function TestMetatable.__index(self,index) return self.DataTable[index] end local Test = TestMetatable.new() -- both functionalities are needed print(Test[1]) Test:TestMethod()
推荐答案
您需要了解__index和__newindex之间的区别,以及它们与主表中 current 内容的关系
You need to understand the difference between __index and __newindex, and their relationship with the current contents of the main table.
__newindex仅在满足以下所有条件时才被调用/访问:
__newindex is only called/accessed when all the following are true:
- 当您通过tbl[index] = expr(或等效语法,如tbl.name = expr)在主表中设置值时.
- 当您尝试设置到主表中的键时主表中不存在.
- When you are setting a value into the main table, via tbl[index] = expr (or equivalent syntax, like tbl.name = expr).
- When the key you are trying to set into the main table does not already exist in the main table.
第二个经常使人绊倒.这就是您的问题,因为在以下情况下只能访问> :
The second one trips people up often. And that's your problem here, because __index is only accessed when:
- 从主表读取的键在主表中尚不存在.
因此,如果要过滤每个读取并写入表的表,则该表必须始终为空.因此,这些读写需要进入为每个新对象创建的 other 表.因此,您的new函数需要创建两个表:一个保留为空,另一个包含所有数据.
So if you want to filter every read from and write to a table, then that table must always be empty. Therefore, those reads and writes need to go into some other table you create for each new object. So your new function needs to create two tables: one that remains empty and one that has all the data in it.
老实说,我希望Lua能够创建一个空的用户数据,您可以将用户定义的元表绑定到其中,以避免这些问题.
Honestly, I wish Lua had a way to create just an empty piece of userdata that you could bind a user-defined metatable to, just to avoid these issues.
这篇关于我需要澄清Metatable .__ index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!