Page 1 of 1

ImageData:getPixel(1, 1) - argument #2 is not a number

Posted: Fri Jul 19, 2019 6:47 pm
by Notnat Tlikehis
I have a canvas (black and white) that represents the lighting in my map. I want to be able to tell when something is in the light or not, so I thought to take the pixel data from the canvas in the middle of the unit. The code I'm using for that is:

Code: Select all

local pixelData = lightcanvas.newImageData(lightcanvas, 1, 1, unit.x*32+16, unit.y*32+16, 1, 1)
local r, g, b, a = pixelData.getPixel(1, 1)
result = (r > 128)
However, it's throwing an error:

Code: Select all

bad argument #2 to ImageData:getPixel (expected number)
From my understanding, that's saying that 1 is not a number? Why am I getting this error and how can I fix it?

Re: ImageData:getPixel(1, 1) - argument #2 is not a number

Posted: Fri Jul 19, 2019 7:53 pm
by Pyuu
I think you need to use:

Code: Select all

local r,g,b,a = pixelData:getPixel(1,1)
The reason for this is because pixelData needs to be the very first argument of the function call (since it's an object). Using : makes the function call reference pixelData as "self" in the underlying function.

Example of this notation:

Code: Select all

function something (b,c)
  self.b = b
  self.c = c
end

local o = {}
o.something = something
o:something(1,2)

print(o.b) -- > 1
print(o.c) -- > 2

Re: ImageData:getPixel(1, 1) - argument #2 is not a number

Posted: Fri Jul 19, 2019 7:54 pm
by raidho36
It's designed to use the colon notation, which would pass the imagedata into the function implicitly as the first argument, as opposed to the dot notation which doesn't implicitly does anything. To compensate, the argument count starts at 0, so "argument #2" actually refers to the argument #3 which you didn't pass.

Code: Select all

pixelData.getPixel ( pixelData, 1, 1 )
pixelData:getPixel ( 1, 1 )

Re: ImageData:getPixel(1, 1) - argument #2 is not a number

Posted: Tue Jul 23, 2019 7:23 pm
by Notnat Tlikehis
Ah, ok, that makes sense. Thanks! That would also explain the discrepancy in arguments between what newImageData actually wants and what the wiki says.

Also I just realized I had this page open with a response typed for several days and never hit submit. Whoops.