Compare multiple var's at the same time

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
MadByte
Party member
Posts: 533
Joined: Fri May 03, 2013 6:42 pm
Location: Braunschweig, Germany

Compare multiple var's at the same time

Post 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 ... ?
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Compare multiple var's at the same time

Post 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

Last edited by kikito on Mon Jun 03, 2013 4:31 pm, edited 1 time in total.
When I write def I mean function.
User avatar
MadByte
Party member
Posts: 533
Joined: Fri May 03, 2013 6:42 pm
Location: Braunschweig, Germany

Re: Compare multiple var's at the same time

Post by MadByte »

Thanks kikito.
Great function !

I didn't expected this problem is that hard to solve :D
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Compare multiple var's at the same time

Post by kikito »

See my edit. There is no real need to use metatables if you are willing to compromise the syntax a bit.
When I write def I mean function.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 1 guest