Lua - Equality Checks on List



We use == operator to compare elements of Lua for equality. We can use __eq() metamethod to implement equality of list using == operator. We can define how to compare elements of the list.

Syntax

__eq(table1, table2)

where

  • table1 represents the first table.

  • table2 represents the second table to be compared with first table.

Example - Comparison of List without __eq() implementation

== operator tries to compare list. It returns false even for same lists as objects are different.

main.lua

local list1 = {1, 2, 3}
local list2 = {1, 2, 3}
local list3 = {3, 2, 1}

-- prints false
print(list1 == list2)

-- prints false
print(list1 == list3)

Output

When we run the above code, we will get the following output−

false
false

Example - Solution to compare list with __eq() implementation

We can implement __eq(table1, table2) metamethod to compare tables−

main.lua

local list1 = {1, 2, 3}
local list2 = {1, 2, 3}
local list3 = {3, 2, 1}

-- create a metatable for equality
local metatableEq = {
   __eq = function(list1, list2)
      if #list1 ~= #list2 then
         return false
      end
      for i = 1, #list1 do
         if list1[i] ~= list2[i] then
            return false
         end
      end
      return true
   end
}

setmetatable(list1,metatableEq )
setmetatable(list2,metatableEq )
setmetatable(list3,metatableEq )

-- prints true
print(list1 == list2)

-- prints false
print(list1 == list3)

Output

When the above code is built and executed, it produces the following result −

true
false

Explanation

  • list1, list2, list3 is used to create a list of strings.

  • local metatableEq is used to create a meta table with __eq() method.

  • __eq = function(list1, list2) is the implementation of metamethod __eq(list1, list2) method.

  • if #list1 ~= #list2 then is used to check lengths of the lists.

  • for i = 1, #list1 do loop runs over list1 items and if list1[i] ~= list2[i] then is used to compare items.

  • If any mismatch occurs, __eq returns false otherwise true is returned.

lua_metatables_with_lists.htm
Advertisements