繁体   English   中英

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

[英]Lua:how to create a custom method on all tables

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

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

谢谢。

在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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM