首页 文章

元元数据?

提问于
浏览
0

我正在尝试在我的表中创建一个__index函数,它可以处理它收到的所有字段 . 我想要做的是,如果我按以下方式调用表

mytable.str1.str2.str3

我应该可以退回 table 了

{"str1", "str2", "str3"}

请注意,str1,str2,str3是未定义的,它们只是字符串 . 我不是要创建子表str1,str2,我只是想让__index看到第一个时期之后的所有内容 .

不幸的是,我有__index只捕获str1,并抱怨“尝试索引字段'str1'(一个零值)”

任何人都知道如何做到这一点?

3 回答

  • 1

    我不确定你为什么要这样做,但这就是你如何做到的 . 注释解释了这个技巧,但基本上你需要第二个metatable来处理从第一次调用__index元方法返回的表 .

    如果不清楚,请告诉我,我可以更详细地解释 .

    -- This metatable appends the new key to itself, then returns itself
    stringtablemeta = {}
    function stringtablemeta.__index(self, key)
        table.insert(self, key)
        return self
    end
    
    -- In response to the question in the comments:
    function stringtablemeta.__tostring(self)
        local str = ""
        for i, v in ipairs(self) do
            if i > 1 then str = str .. "-" end
            str = str .. v
        end
        return str
    end
    
    -- This metatable creates a new table, with stringmetatable as its metatable
    mytablemeta = {}
    function mytablemeta.__index(self, key)
        local temp = { key }
        setmetatable(temp, stringtablemeta)
        return temp
    end
    
    -- set mytable to have mymetatable as it's metatable. This makes it so when    
    -- you index into it, it will call the mytablemeta.__index method.             
    --
    -- That will return a talb with a single string, the key that was passed
    -- in. that table will have it's own metatable, the stringmetatable, which
    -- will cause it to append keys that are called on it with its own __index
    -- metamethod
    mytable = {}
    setmetatable(mytable, mytablemeta)
    
    test = mytable.str1.str2.str3
    
    for k, v in pairs(test) do
        print(k, v)
    end
    
  • 2

    它不能 . 并非每个表都有metatable .

    mytable 是一张 table . str1 是一个不同的表 . 所以你可以通过这样做来做同样的事情:

    local temp = mytable.str1
    temp.str2.str3
    

    就Lua而言,这些是等价的 . 因此,了解每个阶段所做的事情的唯一方法是给所有人提供一个特殊的元素 . 如何将不同的值连接到表中是您必须自己调查的内容 .

  • 1

    正如尼科尔所说,你不能直接在Lua那样做 . 但是,通过返回特制表格,您可以获得与您想要的类似的结果 . 在Lua-users Wiki上查看AutomagicTables获取灵感 .

相关问题