r/lua • u/Weird-Cap-9984 • Nov 18 '25
local variable in interactive mode
Why in the second line, the variable `a` becomes `nil`?
~ $ lua
Lua 5.4.7 Copyright (C) 1994-2024 Lua.org, PUC-Rio
> local a = 123; print(a)
123
> print(a)
nil
8
Upvotes
18
u/clappingHandsEmoji Nov 18 '25
every line in interactive mode is its own chunk, so locals don’t get saved in any way
11
u/weather_isnt_real Nov 18 '25
localis lexically scoped. In this case, the scope is the chunk. Each input to the interpreter is evaluated as a separate chunk and therefore scope.4
u/didntplaymysummercar Nov 18 '25
In addition to what others said (that each line is its own chunk, although if the line you typed isn't a complete chunk you can type in more code in the next one, or ; to force an error) you can also use your own explicit block, typing
doat the start andendat the end.3
u/Vallereya Nov 18 '25
It's how REPL works in Lua, each line is a chunk
3
u/AtoneBC Nov 18 '25
I'm going to assume in the interactive REPL mode, each time you hit enter is its own chunk with its own scope. So the second print can't "see"
abecause it is local to a different scope. If you madeaglobal, it would work. Or if you just made a foo.lua that looked likeand ran
lua foo.luait would work as you expect, because now it's all in the same scope.1
u/vitiral Nov 18 '25
I like to do
L = {}at the start and then useL.foo=whatever()This helps ensure that I don't poison any of the scripts I'm calling with any globals (except L)