__eq metamethod not working?

So I want to make a comparison to return true when I compare an object to nil.

Code:

local null = setmetatable({}, {
	__eq = function(self, Value)
        print("Check!")
		return Value == nil
	end,
})

print(null == nil)
print(null == {})

Output:

Default Lua:
image

Luau:
image


As you can see outputs differ among both languages.

  • Lua documentation states it will not run __eq, if you are comparing your object with nil, function, string, or other native object. However, it runs __eq when you attempt to compare it to another table or userdata.

  • Luau doesn’t say anything at all, so I assume is probably the same behavior. The output claims is different though and it just works when I compare the object to itself.


The documentation on the __eq metamethod in Roblox is no more than “The == equal to operator” which doesn’t help at all with this issue.


The issue with this code is that is not running at all the __eq function in the metatable.

If you know what’s the actual problem in this code please let me know.

2 Likes

Hi, yeah I get the same behavior. Not sure it’s correct. Luau only calls __eq if the two objects have the same metatable. For the usual equality semantics this makes sense, but does limit programmers a bit.

2 Likes

Oof, I wonder why such decision is made when metatables are here to modify how an object behaves, but the equal function gets constrained to just objects with the same metatable then.

Well, thank you! I guess I cannot do that null looking thing. :worried: (I needed a value that I could store in tables as garbage, but not nil because it has some influences over other things. I am currently just using the value false)

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.