Lua为什么禁止在本地var定义上使用goto? [英] Why does Lua prohibit goto over a local var definition?

查看:132
本文介绍了Lua为什么禁止在本地var定义上使用goto?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从手册 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

这将失败,并显示"...跳入本地x的范围"

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

但是为什么呢?如果在使用完本地x之后执行了跳转操作-不再被触摸-因此此处不再需要本地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

当我只用x = 1(在全局范围内制作)切换本地x时,效果很好.

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

是缺少的监督还是优化?例如.也许他们一直认为跳转到标签后可以使用本地var

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

推荐答案

我不太确定如何注册本地人,但是它们是通过数字索引引用的.大概如果使用goto跳过本地定义,那么就永远不会创建本地,因此在标签后尝试访问本地的任何人都将尝试使用无效索引.

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.

您是正确的,从理论上讲,如果从不在标签后使用本地,则不一定不必阻止跳转,但实际上,lua local会一直存在到其作用域结束,而不是消亡最后一次使用后.任何类型的动态代码执行都要求它为真.

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.

但是,您可以使用do -block来限制本地人的范围.使用您的代码,您可以将其重写为

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

这篇关于Lua为什么禁止在本地var定义上使用goto?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆