Why does Lua prohibit goto over a local var definition?

前端 未结 1 1281
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 12:47

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
           


        
相关标签:
1条回答
  • 2021-01-18 13:02

    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
    
    0 讨论(0)
提交回复
热议问题