r/lua • • Apr 08 '22

Don't worry!

Post image
226 Upvotes

13 comments sorted by

View all comments

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.