[英]Why Lua's builtin REPL cannot access previously delcared local vars?
See the following example:请参阅以下示例:
$ lua
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
> local a = 123
> print(a)
nil
This works as expected:这按预期工作:
> local a = 123; print(a)
123
How should I understand the behavior compared to the doc ?与文档相比,我应该如何理解这种行为?
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.
局部变量的 scope 从其声明后的第一条语句开始,一直持续到包含该声明的最内层块的最后一个非 void 语句。
In the Lua REPL, each (multi)line is loaded as an independent chunk via luaL_loadbuffer
.在 Lua REPL 中,每一(多)行通过
luaL_loadbuffer
作为一个独立的块加载。 The same system that makes require("mod_a")
independent of require("mod_b")
.使
require("mod_a")
独立于require("mod_b")
的同一系统。
Therefore, the quoted sentence still applies because every time the REPL prints a >
(compared to a >>
which denotes a multiline ) a new block starts, thereby passing the boundary of "the last non-void statement of the innermost block".因此,引用的句子仍然适用,因为每次 REPL 打印一个
>
(与表示多行的>>
相比)一个新的块开始,从而通过“最内层块的最后一个非空语句”的边界。
Lua REPL treats each line of code as a separate chunk (as if it was a separate Lua file). Lua REPL 将每一行代码视为一个单独的块(就好像它是一个单独的 Lua 文件)。
When a chunk execution is finished, all its local variables are lost.当块执行完成时,其所有局部变量都将丢失。
So, only global variables are preserved between lines.因此,行与行之间只保留了全局变量。
Lua REPL is just a REPL, it is not a debugger, where you would be able to watch and modify all variables while program is running. Lua REPL 只是一个 REPL,它不是调试器,您可以在调试器中查看和修改程序运行时的所有变量。
To use local variables in a multi-line program in Lua REPL: start with do
, enter multiple commands, and finally enter end
to execute the program you entered. Lua REPL中多行程序使用局部变量:以
do
开头,输入多条命令,最后输入end
执行你输入的程序。
$ lua
Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
> do
>> local a = 123
>> print(a)
>> end
123
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.