2009-05-05

Lua constants

By Lua's nature, it is not possible to create constants. There is a workaround, though, using metatables:

function protect(tbl)
    return setmetatable({}, {
        __index = tbl,
        __newindex = function(t, key, value)
            error("attempting to change constant " ..
                   tostring(key) .. " to " .. tostring(value), 2)
        end
    })
end

constants = {
    x = 1,
    y = 2,
}
constants = protect(constants)

print(constants.x) --> 3
constants.x = 3 --> error: attempting to change constant x to 3

No comments:

Post a Comment