为什么 Lua 禁止转到本地 var 定义? [英] Why does Lua prohibit goto over a local var definition?

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

问题描述

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

这是疏忽还是缺少优化?例如.也许他们总是假设在跳转到标签后可以使用本地变量

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本地存在直到其范围结束,而不是死亡在最后一次使用之后.任何类型的动态代码执行都要求这是真的.

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 块来限制本地人的范围.使用您的代码,您可以将其重写为

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 定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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