Zum Inhalt springen

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:

„`lua

local a = 1

function f() 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

fn main() { let mut a = 1;

//I Know this one is as bad as a rust block can get, but it proves my point!

fn f(a: &mut i32) -> i32 { *a += 1; *a } println!("{}", a + f(&mut a)); // compiler error here! 

} „`

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!

P.S: I tried to recreate lua’s runtime, in rust I Know terminology and implementing is not accurate!

submitted by /u/DisplayLegitimate374
[link] [comments]

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert