immutability - How to code a run-time, single-assignment, variable in Lua? - Stack Overflow

admin2025-04-28  2

I am interested in knowing how to code a single assignment variable in Lua, similar to this example in Rust.

fn main() {
    println!("Hello, world!");
    let x; //---> This is the single assignment variable
    let y = 20;
    x = 10;
    x = 20; //---> This will cause a compiler error
    println!("{} + {} = {}",x,y,x+y);
    
}

I am interested in knowing how to code a single assignment variable in Lua, similar to this example in Rust.

fn main() {
    println!("Hello, world!");
    let x; //---> This is the single assignment variable
    let y = 20;
    x = 10;
    x = 20; //---> This will cause a compiler error
    println!("{} + {} = {}",x,y,x+y);
    
}
Share Improve this question asked Jan 9 at 18:47 Milind Daller-BussiMilind Daller-Bussi 14211 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

In Lua 5.4, a local declaration may contain the <const> attribute, creating a constant variable.

Attempting to reassign a constant variable throws an error:

local foo <const> = 42
foo = 99 -- error: attempt to assign to const variable 'foo'

Lua 5.4: 3.3.7 – Local Declarations

转载请注明原文地址:http://anycun.com/QandA/1745779631a91182.html