gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:05:26 24 4
gpt4 key购买 nike

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

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

谢谢。

最佳答案

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

关于Lua:如何在所有表上创建自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com