Page 1 of 1

Compare multiple var's at the same time

Posted: Mon Jun 03, 2013 4:15 pm
by MadByte
Hi,

simple question. I'm searching for a good way to compare the output of getPixel with my vars. I tried this one:

Code: Select all

r, g, b, a = img:getPixel( x, y )
if r, g , b, a == 255, 0, 0 , 255 then
 -- do stuff
end
I thought this would work because declare vars like that also work. I know that this ..

Code: Select all

if r = 255 and b == 0 and g == 0 and a == 255 then
  -- do stuff
end
.. does work but isn't there an easier way to compare them? :/
Maybe put them into a table or similar ... ?

Re: Compare multiple var's at the same time

Posted: Mon Jun 03, 2013 4:26 pm
by kikito

Code: Select all

 -- name this file arrr.lua
local mt = {
  __eq = function(self, other)
    local l1,l2 = #self, #other
    if l1 ~= l2 then return false end
    for i=1, l1 do
      if self[i] ~= other[i] then return false end
    end
    return true
  end
}
local arrr = function(...)
  return setmetatable({...}, mt)
end
return arrr
Usage:

Code: Select all

local arrr = require 'arrr'
r, g, b, a = img:getPixel( x, y )
if arrr(r, g , b, a) == arrr(255, 0, 0 , 255) then
 -- do stuff
end
Arrr.

Edit: In all honesty, I prefer a more verbose but clear approach:

Code: Select all

local arrayEqual = function(self, other)
    local l1,l2 = #self, #other
    if l1 ~= l2 then return false end
    for i=1, l1 do
      if self[i] ~= other[i] then return false end
    end
    return true
end
...

r, g, b, a = img:getPixel( x, y )
if arrayEqual({r, g , b, a}, {255, 0, 0 , 255}) then
 -- do stuff
end


Re: Compare multiple var's at the same time

Posted: Mon Jun 03, 2013 4:30 pm
by MadByte
Thanks kikito.
Great function !

I didn't expected this problem is that hard to solve :D

Re: Compare multiple var's at the same time

Posted: Mon Jun 03, 2013 4:32 pm
by kikito
See my edit. There is no real need to use metatables if you are willing to compromise the syntax a bit.