【问题标题】:Lua:how to create a custom method on all tablesLua:如何在所有表上创建自定义方法
【发布时间】:2012-10-01 09:51:28
【问题描述】:

我想在 Lua 的 table 数据结构上创建一个自定义 contains 方法,用于检查密钥是否存在。用法如下所示:

mytable  = {}
table.insert(mytable, 'key1')
print(mytable.contains('key1'))

谢谢。

【问题讨论】:

    标签: lua


    【解决方案1】:

    在 Lua 中,您不能一次更改所有表。您可以使用更简单的类型来执行此操作,例如数字、字符串、函数,您可以在其中修改它们的元表并向所有字符串、所有函数等添加方法。这已经在 Lua 5.1 中针对字符串完成,这就是您可以这样做的原因这个:

    local s = "<Hello world!>"
    print(s:sub(2, -2)) -- Hello world!
    

    表和用户数据对于每个实例都有元表。如果您想创建一个已经存在自定义方法的表,那么简单的表构造函数将无法完成。然而,使用 Lua 的语法糖,你可以这样做:

    local mytable = T{}
    mytable:insert('val1')
    print(mytable:findvalue('val1'))
    

    为了实现这一点,您必须在使用T之前编写以下内容:

    local table_meta = { __index = table }
    function T(t)
        -- returns the table passed as parameter or a new table
        -- with custom metatable already set to resolve methods in `table` 
        return setmetatable(t or {}, table_meta)
    end
    
    function table.findvalue(tab, val)
        for k,v in pairs(tab) do
            -- this will return the key under which the value is stored
            -- which can be used as a boolean expression to determine if
            -- the value is contained in the table
            if v == val then return k end
        end
        -- implicit return nil here, nothing is found
    end
    
    local t = T{key1='hello', key2='world'}
    t:insert('foo')
    t:insert('bar')
    print(t:findvalue('world'), t:findvalue('bar'), t:findvalue('xxx'))
    if not t:findvalue('xxx') then
        print('xxx is not there!')
    end
    
    --> key2    2
    --> xxx is not there!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 2015-02-09
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多