Bug? Or error in my code?

So today, I was making a program in Codea that would take the image on the pasteboard, divide it into sections, and take the most prominent color in each section, and make that a pixel on an image. So I expected this to work perfectly, but I get this wierd error. For the function getColorCode() that’s near the bottom, it says that I need an “end” statement to end the function. The thing is, I already have that there.

-- Pixelizer

-- Use this function to perform your initial setup
function setup()
    i = pasteboard.image
    parameter.integer("resultWidth", 1, 32)
    parameter.action("Start", getPixelImage)
end

-- This function gets called once every frame
function draw()
    background(255, 255, 255, 255)
    sprite(i, WIDTH / 2, HEIGHT / 2, WIDTH, HEIGHT)
end

function getPixelImage()
    local w, h = spriteSize(i)
    local p = {}
    for x = 1, resultWidth do
        p[x] = {}
        for y = 1, resultWidth do
            local bound1 = vec2(math.floor(((x - 1) / resultWidth) * w), math.floor(((y - 1) / resultWidth) * h))
            local bound2 = vec2(math.floor((x / resultWidth) * w), math.floor((y / resultWidth) * h))
            local col = {}
            for x2 = bound1.x, bound2.x do
                for y2 = bound1.y, bound2.y do
                    local getCol = i:get(x2, y2)
                    local code = getColorCode(getCol)
                    if col[code] == nil then
                        col[code] = 1
                    else
                        col[code] = col[code] + 1 
                    end
                end
            end
            local highest = 0
            local colHighest = 0
            for k, v in pairs(col) do
                if v > highest then
                    highest = v
                    colHighest = k
                end
            end
            p[x][y] = getColor(colHighest)
        end
    end
    local setTo = image(resultWidth, resultWidth)
    for x, yt in pairs(p) do
        for y, col in pairs(yt) do
            setTo:set(x, y, col)
        end
    end
    i = setTo
end

function getColorCode(col)
    return col.a * 16777216 col.r * 65536 + col.g * 256 + col.b
end

function getColor(code)
    local a = math.floor(code / 16777216)
    local r = math.floor(code / 65536) % 256
    local g = math.floor(code / 256) % 256
    local b = code % 256
    return color(r, g, b, a)
end

Is this a bug with Codea, or just a typo in my own code? By the way, I’ve tried finding the error in my code (if there is any).

It’s an error in your code. i:get(x2,y2) returns 4 values (r,g,b,a), not 1 value. Also, you forgot the + after 16777216 in that function.

@dave1707 Thanks! I didn’t notice these 2 things. I also sometimes forget about image:get() returning 4 values.

So I expected this to work perfectly

That’s your mistake right there :stuck_out_tongue: