Search code examples
luaread-eval-print-loop

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.


Solution

  • 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".