Lua-两个具有相同名称的局部变量 [英] Lua - Two local variables with the same name

查看:194
本文介绍了Lua-两个具有相同名称的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习 Lua ,我想知道是否允许它引用两个同名的局部变量.

I have been learning Lua and I was wondering if it is allowed to reference two local variables of the same name.

例如,在下面的代码段中,语法是否合法(没有未定义的行为)?

For example, in the following code segment, is the syntax legal (without undefined behavior)?

我问,因为它确实在运行,但是我似乎无法弄清楚幕后正在发生什么.这是否只是引用相同的本地x?还是现在有两个local x变量使幕后混乱.我想知道这里到底发生了什么,为什么会这样.

I ask because it does run, but I cannot seem to figure out what is happening behind the scenes. Is this simply referencing the same x local? Or are there now two local x variables that mess things up behind the scenes. I'd like to know what exactly is happening here and why it is the case.

local x = 5 + 3; -- = 8
local x = 3 - 2; -- = 1

print("x = " .. x); -- x = 1

推荐答案

有两个变量.第二个阴影(但不会删除或覆盖)第一个阴影.

There are two variables. The second shadows (but does not remove or overwrite) the first.

有时候,您仍然可以通过闭包访问早期的定义.

Sometimes you can still access the earlier definition via a closure.

local x = 5 + 3
local function getX1()
  return x
end
local x = 3 - 2
local function getX2()
  return x
end

print("x = " .. x); -- x = 1
print("x = " .. getX1()); -- x = 8
print("x = " .. getX2()); -- x = 1

这篇关于Lua-两个具有相同名称的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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