admin管理员组

文章数量:1124168

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 yesterday ggg123ggg123 14411 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

本文标签: immutabilityHow to code a runtimesingleassignmentvariable in LuaStack Overflow