Lua中的范围规则

Lua中的范围规则,第1张

概述我正在测试Lua的范围并注意到一些意外的事情.以下代码不会打印localMainVariable. function functionScope() print( "\nIn function") print( "globalMainVariable: " .. globalMainVariable ) if (localMainVariable ~= nil) then 我正在测试Lua的范围并注意到一些意外的事情.以下代码不会打印localMainVariable.

function functionScope()    print( "\nIn function")    print( "globalMainVariable: " .. globalMainVariable )    if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable ) endendglobalMainVariable = "Visible"local localMainVariable = "Visible"functionScope()

但是下面的代码确实打印了localMainVariable.

globalMainVariable = "Visible"local localMainVariable = "Visible"function functionScope()    print( "\nIn function")    print( "globalMainVariable: " .. globalMainVariable )    if (localMainVariable ~= nil) then print( "localMainVariable: " .. localMainVariable )  endendfunctionScope()

我知道它与声明localMainVariable的位置有关,但我认为将其设置为local会限制变量的范围.什么是实际规则

谢谢

解决方法

The scope of a local variable begins at the first statement after its
declaration and lasts until the last non-voID statement of the
innermost block that includes the declaration.

Lua manual

总结

以上是内存溢出为你收集整理的Lua中的范围规则全部内容,希望文章能够帮你解决Lua中的范围规则所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1224677.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存