lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Mon, Apr 24, 2017 at 11:07 Bill Kelsoe <wildbillkelsoe@gmail.com> wrote:
In Chapter 3 concerning relational operators expressions, PIL says that "if values have different types, Lua considers them not equal"

So if I understood this, this means that if a boolean and a string are related, using ~= , means that they are like apples and oranges?

Because right after that statement, "Otherwise, Lua compares them according to their types."

So if a value is Boolean meaning either true or false, and the other comparator is a String, of the value "true", so they are evaluated equal by Lua even if ~= is used?

hope I understood it correctly.

No. 

If two values are of different types (one is a table and one is not a table), then they will not be equal. They will not be equally, even if the table has a metatable with the metamethod:

My.__eq = function() return true end

In part, this is why the paragraph exists: to explain the limitation of the __eq metamethod, which is only called when both types are equal. 

Consider a complex number library that produces a value that can hold both complex and non-complex numbers: 

c = complex.new(3) --returns an object that represents a complex number. 
if c == 3 then 
  print "will execute."
else
  print "will execute."
end

This is because Lua will never check for the existence of an __eq metamethod because the type of the value of "c" is "table" (or userdata, depending on how the library is implemented) and the value of the literal "3" is "number."

Inequality is treated the same way.