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
5
u/lambda_abstraction Apr 09 '22 edited Apr 09 '22
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 }) endPairs and ipairs support left as an exercise for the reader.
12
14
4
3
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
1
u/makingthematrix Apr 09 '22
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.
Is there something like this for Lua?
32
u/tf2ftw Apr 08 '22
Use all caps. If it’s all caps don’t try to assign a value. o.O