我正在寻找Lua 5.1中与metatables比较的方法,因此我可以将任何值与表进行比较。如果该值在表中,则返回true,如果不在表中,则返回false。如下。
if table == string then
-- does something if string is in the table
end
我知道使用了__eq
,但参考手册中有关于确保2是相同类型且具有相同__eq
功能的内容。要做到这一点,我需要克服这个限制,我不知道如何,甚至不可能。
答案 0 :(得分:2)
无需修改Lua源代码,您就无法做到。 Lua在比较两个值时检查的第一件事是检查它们的类型。如果类型不匹配,则结果为false而不检查matatable。
我不认为这样做是个好主意,因为它打破了平等的共同规则:如果a
和b
相等,{{1} }和b
相等,则c
和a
应该相等。但是在你的情况下,它不是那样的,例如,该表包含两个字符串c
和"foo"
,所以它等于两个字符串,但两个字符串显然不相等。
为什么不使用"bar"
运算符以外的简单函数。我使用==
而不是contains
对其进行了命名,因为这是对此功能的正确描述。
equals
答案 1 :(得分: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
...