Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Lua prohibit goto over a local var definition?

Tags:

lua

I read this from the manual http://lua-users.org/wiki/GotoStatement

I have a similar code block in a loop:

while true do
  if someCond == nil then
      goto f  -- invalid (forward jump into scope of local definition)
  end

  local x = 1
   -- do something with x
  ::f::
end

This will fail with "...jumps into the scope of local x"

But why? if the jump is executed its after any usage of local x - it is not touched anymore - hence "local x" is not required anymore here

When i switch local x with just x = 1 (making in global) it works fine.

Is that an oversight or an optimization that is missing ? E.g. maybe they always assume that a local var could possible be used after jumping to the label

like image 522
Steve Avatar asked Jan 24 '13 23:01

Steve


1 Answers

I'm not quite sure how locals are registered, but they're referenced via a numeric index. Presumably if one were to use a goto to skip past a local definition, then the local would never be created, and therefore anyone trying to access the local after the label would be attempting to use an invalid index.

You are right that in theory, if the local is never used after the label, then it doesn't necessarily have to prevent the jump, but in practice, a lua local exists until the end of its scope, rather than dying after its last usage. Any sort of dynamic code execution requires this to be true.

However, you can use a do-block to restrict the scope of your locals. With your code, you would rewrite this as

while true do
  if someCond == nil then
      goto f
  end

  do
      local x = 1
       -- do something with x
  end -- x is now gone
  ::f::
end
like image 131
Lily Ballard Avatar answered Sep 26 '22 19:09

Lily Ballard