r/lua • u/DisplayLegitimate374 • May 25 '25
Discussion Lua's scoping behavior can be quite surprising. Bug or by design?!!
Please correct me! I haven't really used lua for a full project but I have played with it here and there! Alongside my nvim configuration.
But this is what I'm really confused about:
local a = 1
a = a + 1
return a
end
print(a + f())
The above code prints 4.
However, if a is not declared as local, it prints 3 (hmm).
I mean I try to get it, it's the lexical scoping and that the reference to a remains accessible inside f(). Still, from a safety standpoint, this feels error-prone.
Technically, if a is declared as local, and it's not within the scope of f(), the function should not be able to access or mutate. it should panic.
But it reads it and doesn't mutate globally (I guess that's should've been the panic )
To me, the current behavior feels more like a quirk than an intentional design.
I am familiar with rust so this is how I translated it :
Rust will reject this code at compile time because you're trying to borrow a as mutable while it's still being used in the expression a + f(&mut a).
And I assume gcc would throw a similar complier error!
16
u/appgurueu May 25 '25 edited May 25 '25
TL;DR: Not a bug, has nothing to do with scoping. This is explicitly permitted by Lua's design.
It's just an implementation detail related to evaluation order that happens to depend on whether it's a local variable.
Don't assume, test:
gcccompiles this just fine. No warning, no error. Here's the code:This gives an exit code of 4. Feel free to play with compiler flags; ubsan doesn't seem to catch this. I'm pretty sure this is just undefined behavior in C.
And it's a similar story in Lua: No particular order of evaluation is guaranteed. Maybe Lua first evaluates the right operand; then you would get
4. Maybe it first evaluates the left operand; then you would get3. Your code simply relies on something it should not rely on.The problem in your code snippet is not Lua's lexical scoping. That is perfectly reasonable:
ais lexically visible inside the function, so you can access and mutate it. A local value from a parent scope that's accessible in a function is called an upvalue; the instance of the function bound to that variable is called a closure. Closures are a very powerful tool.If you simply wrote
you would be guaranteed to get 4.
The comparison with Rust doesn't pan out. Lua is a scripting language. It's main goals are expressive power, conciseness, simplicity. If you wanted to optimize for safety, the first thing to go would be dynamic typing. But that would significantly hurt the other goals, so a scripting language doesn't do it.
In the world of scripting languages, suggesting that using upvalues should panic is rather absurd: It would just be unnecessarily neutering the language, and messing up the otherwise intuitive lexical scoping with a special case rule.
This is not a problem of closures; it's a problem of order of execution and side effects (mutability). A tool like the borrow checker can help with that - but will also hurt completely valid language usage, e.g. by disallowing aliasing, which may very well be intended.
Now, if you want to study the implementation details (which you should not rely on!), you can simply look at the bytecode.
If you use a global variable, PUC Lua decides to first fetch the global variable, then call the function. It looks like this in bytecode:
(you can get such a listing from
luac -l program.lua)If however you use a local variable (upvalue), PUC Lua simply calls the function - since it knows it still has the local variable on the stack:
Note that by the time the
ADDexecutes, the call tofhas already mutated the local variable.If Lua was not free to choose an order of execution, it would have had to copy
afirst to ensure right-to-left execution, wasting a VM cycle. Furthermore, in an optimized implementation like LuaJIT, this may inhibit other optimizations.Arguably, code like the above also really very often shouldn't be a thing: If you need a particular order of execution due to side effects, you should write multiple statements to make it explicit.
Reasons like this are what ultimately led the Lua authors to leave evaluation order undefined:
http://lua-users.org/lists/lua-l/2006-06/msg00378.html
14
u/rhodiumtoad May 25 '25
This is about execution order, not scope.
The bytecode generated for a+f() seems to use a different order depending on whether
ais a local, presumably becauseais already in a "register" slot so a+f() becomes "call f and add to the result the slot containing the (now mutated)a". You'd have to look at the bytecode with luac to confirm this (I can't be bothered to check).That locals of outer scopes are visible to functions is completely intentional and is an important language feature, since it's how closures work. If you've only used languages that lack closures then you might not appreciate their importance.
The execution order of expressions is (mostly) not guaranteed by Lua, so expressions that both read and mutate the same object may return unexpected results.
3
u/AtoneBC May 25 '25
I'm not smart enough to tell you exactly what's happening here with the order of evaluation of print's arguments. But in this scenario,
f()being able to accessais intentional. That's how you do closures. It does mutate the originala. Add aprint(a)at the very end and see that it is now 2.1
u/AutoModerator May 25 '25
Hi! Your code block was formatted using triple backticks in Reddit's Markdown mode, which unfortunately does not display properly for users viewing via old.reddit.com and some third-party readers. This means your code will look mangled for those users, but it's easy to fix. If you edit your comment, choose "Switch to fancy pants editor", and click "Save edits" it should automatically convert the code block into Reddit's original four-spaces code block format for you.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/4xe1 May 26 '25 edited May 26 '25
Just to comment about the rust thing, functions in lua (and in most dynamic languages) correspond to your closures, not to your compiled functions. They are implicitly allowed to capture values by default.
A better Rust translation is:
The compiler error has little to do with scoping. It errors because the closure f borrows a mutably. It still does prevent the bad code you're writing from unexpectedly working. You have to use inner mutability explicitly if that's what you're after. That's intentional, but that Rust behaviour is somewhat niche among other programming languages.
println!("{}", f() + a);Actually works (and yields 4), because f "dies" soon enough.
-2
u/[deleted] May 26 '25
Just because its by design, doesn't mean its not a bug.
0
u/[deleted] May 25 '25
[deleted] — view deleted comment