【问题标题】:Compare a value with a table by using metatables in Lua使用 Lua 中的元表将值与表进行比较
【发布时间】:2014-03-20 21:58:44
【问题描述】:

我正在 Lua 5.1 中寻找一种与元表进行比较的方法,因此我可以将任何值与表进行比较。如果该值在表中,则返回 true,如果不在表中,则返回 false。像下面这样。

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

我知道使用了__eq,但参考手册统计了一些关于确保2 是相同类型并具有相同__eq 功能的信息。要做到这一点,我需要克服这个限制,我不知道如何,甚至不知道它是否可能。

【问题讨论】:

  • 您可以重新定义(使用元表)任何其他运算符:+-*/%^<if table(string) then .
  • table == string 是无耻的运算符滥用,例如将* 重新定义为减法。将“包含”方法添加到您的表(或者它是元表的)。

标签: lua lua-table metatable


【解决方案1】:

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

而且我认为这样做不是一个好主意,因为它违反了平等的共同规则:如果 ab 相等,bc 相等,则 @987654325 @ 和 c 应该相等。但是你的情况不是这样的,比如表中包含两个字符串"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

【讨论】:

    【解决方案2】:

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

    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
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 2013-07-14
      • 2021-01-23
      • 1970-01-01
      • 2019-03-24
      • 2016-05-02
      相关资源
      最近更新 更多