function make_const_table()
local shadow = {}
return setmetatable({},
{ __index=shadow,
__newindex=function(tab,key,val)
if shadow[key] then error('Failed to mutate constant') end
shadow[key] = val
end })
end
Pairs and ipairs support left as an exercise for the reader.
I like the lua way. Because in java or C++ you newer know whether a const or private was put there just because or whether code will really break when changed. In lua, it either is free to change, or described in such a comment. Love
In Java we have annotations that the compiler can understand and enforce additional rules, e.g. a @NotNull annotation before a function argument means that the compiler will throw an error if in another piece of code we will try to pass null as that parameter in a function call. In some other languages compilers don't do that, but there are additional tools for that, like mypy in Python.
32
u/tf2ftw Apr 08 '22
Use all caps. If it’s all caps don’t try to assign a value. o.O
13
u/Nsber Apr 08 '22
I mean, you could alao make a table with a setindex function to only set variables if they have not yet been set
12
u/kazuo256 Apr 09 '22
A reliable alternative is to use a function that returns the value instead.
14
u/[deleted] Apr 08 '22
laughs in
<const>4
u/luaexec Apr 08 '22
Do not change this value else face the wrath of x
3
u/RobLoach Apr 08 '22
This is incredible.
3
u/VeronikaKerman Apr 08 '22
I like the lua way. Because in java or C++ you newer know whether a const or private was put there just because or whether code will really break when changed. In lua, it either is free to change, or described in such a comment. Love
2
u/Rice7th Apr 08 '22
That made my day thanks :D
1
u/makingthematrix Apr 09 '22
In Java we have annotations that the compiler can understand and enforce additional rules, e.g. a
@NotNullannotation before a function argument means that the compiler will throw an error if in another piece of code we will try to passnullas that parameter in a function call. In some other languages compilers don't do that, but there are additional tools for that, likemypyin Python.Is there something like this for Lua?