简体   繁体   中英

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.

In the Lua REPL, each (multi)line is loaded as an independent chunk via luaL_loadbuffer . The same system that makes require("mod_a") independent of 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".

Lua REPL treats each line of code as a separate chunk (as if it was a separate Lua file).
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.

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
Lua 5.4.3  Copyright (C) 1994-2021 Lua.org, PUC-Rio
> do
>> local a = 123
>> print(a)
>> end
123
>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM