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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Termanater13
  • 45
  • 1
  • 8
  • You can redefine (using metatables) any other operator: `+`, `-`, `*`, `/`, `%`, `^`, `<` or `if table(string) then`. – Egor Skriptunoff Mar 18 '14 at 16:14
  • `table == string` is shameless operator abuse, like redefining `*` to mean subtraction. Add a "contains" method to your table (or it's metatable). – Mud Mar 18 '14 at 17:56

2 Answers2

2

Without modifying the Lua source code, you can't. The first thing Lua checks when comparing two values is to check their types. If the type mismatch, the result is false without checking the matatable.

And I don't think it's a good idea to do this, because it breaks the common rules of equality: if a and b are equal, b and c are equal, then a and c should be equal. But in your case it's not like that, for instance, the table contains two strings "foo" and "bar", so it's equal to both the two strings, but the two strings are obviously not equal.

Why not just use a simple function other than == operator. I named it with contains instead of equals because that's the correct description of this function.

function contains(t, value)
    for _, v in pairs(t) do
        if v == value then
            return true
        end
    end
    return false
end
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

The simplest way to do what you want is ensuring that both terms are tables in the first place.

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

However, I must warn you against doing this. If, as you said, you want to 'check that a is inside b', I would not use the equality operator for that. Instead, I would use something more explicit, like:

if tableContains(b,a) then -- this is less confusing; equality doesn't mean composition
...
kikito
  • 51,734
  • 32
  • 149
  • 189