ggg123
ggg123

Reputation: 142

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

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);
    
}

Upvotes: -2

Views: 57

Answers (1)

Oka
Oka

Reputation: 26365

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

Upvotes: 3

Related Questions