1

I'm looking for a way in Lua 5.1 to compare with metatables, so I can compare any value with a table. If that value is in the table it returns true, and false if it is not in the table. like the following.

if table == string then
  -- does something if string is in the table
end

I know that the __eq is used, but the reference manual stats something about making sure that the 2 be the same type and have the same __eq function. To do this I would need to overcome that limitation and I do not know how, or even if it is even possible.

4

2 回答 2

2

不修改 Lua 源代码是不行的。Lua 在比较两个值时检查的第一件事是检查它们的类型。如果类型不匹配,则结果为 false,无需检查 matatable。

而且我认为这样做不是一个好主意,因为它违反了平等的共同规则:如果ab相等,b并且c相等,那么ac应该相等。但是在您的情况下,情况并非如此,例如,表包含两个字符串"foo""bar",因此它等于两个字符串,但是这两个字符串显然不相等。

为什么不只使用==运算符以外的简单函数。我将其命名为,contains而不是equals因为这是对这个函数的正确描述。

function contains(t, value)
    for _, v in pairs(t) do
        if v == value then
            return true
        end
    end
    return false
end
于 2014-03-17T06:27:25.563 回答
0

做你想做的最简单的方法是首先确保这两个术语都是表格。

local a = "a string"
local b = {"a table", "containing", "a string"}

...

-- Make sure that a is a table
if type(a) ~= 'table' then a = {a} end

if a == b then -- now you can use metatables here
...

但是,我必须警告你不要这样做。如您所说,如果您想“检查 a 是否在 b 内”,我不会为此使用相等运算符。相反,我会使用更明确的东西,例如:

if tableContains(b,a) then -- this is less confusing; equality doesn't mean composition
...
于 2014-03-17T15:54:04.400 回答