Lua:如何在所有表上创建自定义方法
我想在Lua的Lua:如何在所有表上创建自定义方法,lua,Lua,我想在Lua的表数据结构上创建一个自定义的contains方法来检查是否存在键。用法如下所示: mytable = {} table.insert(mytable, 'key1') print(mytable.contains('key1')) local mytable = T{} mytable:insert('val1') print(mytable:findvalue('val1')) 谢谢。在Lua中,您不能一次更改所有表。您可以使用更简单的类型(如数字、字符串、函数)执行此操作
表
数据结构上创建一个自定义的contains方法来检查是否存在键。用法如下所示:
mytable = {}
table.insert(mytable, 'key1')
print(mytable.contains('key1'))
local mytable = T{}
mytable:insert('val1')
print(mytable:findvalue('val1'))
谢谢。在Lua中,您不能一次更改所有表。您可以使用更简单的类型(如数字、字符串、函数)执行此操作,您可以修改它们的元表,并向所有字符串、所有函数等添加一个方法。这已在Lua 5.1中针对字符串完成,这就是您可以执行此操作的原因:
local s = "<Hello world!>"
print(s:sub(2, -2)) -- Hello world!
为了实现这一点,您必须在使用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!