Vincent Li
Vincent Li

Reputation: 11

Basic Lua problem - A if statement nested in for loop

I am an amateur in Lua, l wrote this code but fail to compile, l have checked the structure of the syntax and found that it was a match, so l really do not know what is wrong, it says that 18: 'end' expected (to close 'if' at line 16) near 'startFishing' but why should l do that????? BTW startFishing is another function that l defined previously in the same file.

function detectSuccess()
    local count = 0;
    for x = 448, 1140, 140 do
        color = getColor(x, 170);
        if color == 0xffffff then 
            return false
            startFishing()
        else
            return true
        end
    end
end

Upvotes: 1

Views: 601

Answers (2)

mksteve
mksteve

Reputation: 13085

Formatting code correctly we have ....

function detectSuccess()
   local count = 0;
    for x = 448, 1140, 140 do
        color = getColor(x, 170);
        if color == 0xffffff then 
            return false
            startFishing()
        else
            return true
        end
    end
end

detectSuccess()

The startFishing() statement is dangling. syntactically the only thing that can come after return, is the else or end.

That is the complaint from the lua parser.

From lua : programming in lua 4.4

For syntactic reasons, a break or return can appear only as the last statement of a block (in other words, as the last statement in your chunk or just before an end, an else, or an until).

If you want startFishing to be called, it needs to be before the return. e.g.

function detectSuccess()
   local count = 0;
    for x = 448, 1140, 140 do
        color = getColor(x, 170);
        if color == 0xffffff then 
            startFishing() -- moved before the return
            return false
        else
            return true
        end
    end
end

Upvotes: 6

lhf
lhf

Reputation: 72412

You can't have a statement in the same block after a return. I guess you mean this instead:

if color == 0xffffff then 
   startFishing()
   return false
else
   return true
end

Indenting your code will help you seeing syntax problems.

Upvotes: 4

Related Questions