Not sure what to do with this error. -lua Language

-- Use "if" and "else if" to handle any situation.
-- Put it all together to defeat enemies and pick up coins!
-- Make sure you bought great armor from the item shop! 400 health recommended.

loop
    local flag = self:findFlag()
    local enemy = self:findNearestEnemy()
    local item = self:findNearestItem()
    local pos = item.pos
        local x = pos.x
        local y = pos.y
    if flag then
        -- What happens when I find a flag?
        self:pickUpFlag(flag)
    elseif enemy then
        -- What happens when I find an enemy?
        if self:isReady("cleave") then
            self:cleave(enemy)
            else
                self:attack(enemy)
            end
            end
    elseif item then
        self:moveXY(pos.x, pos.y)
        -- What happens when I find an item?
        end
    end
end

Error: end expected (to close if at 23:5) at 23:5)

Why is this and how can I fix it? Nothing I know I can do seems to work.

I’m willing to try and reply as complete as I can to questions.

When in doubt, call @nick

You have an extra end right before your elseif item then line, because you indented the preceding else one level too deeply. Try making your indentation perfect and it’s easy to see when things aren’t matched like this. Hope this helps!

This helped, thank you very much!