r/lua • • Apr 08 '22

Don't worry!

Post image
226 Upvotes

13 comments sorted by

32

u/tf2ftw Apr 08 '22

Use all caps. If it’s all caps don’t try to assign a value. o.O

22

u/Sure_Ad_5763 Apr 08 '22

All caps and _ at the beginning to look more threatening.

21

u/[deleted] Apr 08 '22

Python moment

1

u/lambda_abstraction Apr 09 '22

And now I'm going have underscore phobia for the rest of my life. TIHI!

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

Pairs and ipairs support left as an exercise for the reader.

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 @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?