sceiler
sceiler

Reputation: 1205

Why does if then return break end not work in Lua inside for loop

I have the following function which checks if the given parameter is found as a key in a key-value table. If that is the case it should return true and break out of the loop. If nothing is found then do nothing.

function checkId(id)
  for k,v in pairs(info) do
    if id == tostring(k) then
      return true
      break -- break out of loop. mission accomplished.
    end
  end
end

I get an

'end' expected (to close 'do' at line 192) near 'break'

when I try to run this script. What am I missing?

Upvotes: 0

Views: 4283

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80921

Logically you can't return and break like that.

return exits the function immediately (so you don't need the break).

That specific error is because in lua return has to be the last statement in a block.

Upvotes: 5

Related Questions