Lua:如何在所有表上创建自定义方法

时间:2012-10-01 09:51:28

标签: lua

我想在Lua的table数据结构上创建一个自定义包含方法,以检查是否存在密钥。用法看起来像这样:

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

感谢。

1 个答案:

答案 0 :(得分:7)

在Lua中,您无法一次更改所有表格。您可以使用更简单的类型(如数字,字符串,函数)执行此操作,您可以在其中修改其元表并向所有字符串,所有函数等添加方法。这已经在Lua 5.1中为字符串完成,这就是为什么你可以做的这样:

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

表和userdata具有每个实例的元表。如果要创建一个已经存在自定义方法的表,则不会使用简单的表构造函数。但是,使用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!