Lua:如何在所有表上创建自定义方法 [英] Lua:how to create a custom method on all tables

查看:128
本文介绍了Lua:如何在所有表上创建自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to create a custom contains method on Lua's table data structure that would check for the existence of a key. Usage would look something like this:

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

谢谢.

推荐答案

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

In Lua you cannot change ALL tables at once. You can do this with simpler types, like numbers, strings, functions, where you can modify their metatable and add a method to all strings, all functions, etc. This is already done in Lua 5.1 for strings, this is why you can do this:

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

表和用户数据具有每个实例的元表.如果要使用已经存在的自定义方法创建表,则简单的表构造函数将不起作用.但是,使用Lua的语法糖,您可以执行以下操作:

Tables and userdata have metatables for each instance. If you want to create a table with a custom method already present, a simple table constructor will not do. However, using Lua's syntax sugar, you can do something like this:

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

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

In order to achieve this, you have to write the following prior to using 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!

这篇关于Lua:如何在所有表上创建自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆