is there any keyword like const or anything else which does the same job with it in lua?

Lua does not support constants automatically, but you can add that functionality. For example by putting your constants in a table, and making the table read-only using metatable.

Here is how to do it: http://andrejs-cainikovs.blogspot.se/2009/05/lua-constants.html

The complication is that the names of your constants will not be merely "A" and "B", but something like "CONSTANTS.A" and "CONSTANTS.B". You can decide to put all your constants in one table, or to group them logically into multiple tables; for example "MATH.E" and "MATH.PI" for mathematical constants, etc.


I know this question is seven years old, but Lua 5.4 finally brings const to the developers!

local a <const> = 42
a = 100500

Will produce an error:

lua: tmp.lua:2: attempt to assign to const variable 'a'

Docs: https://www.lua.org/manual/5.4/manual.html#3.3.7.


As already noted there is no const in Lua.

You can use this little workaround to 'protect' globally defined variables (compared to protected tables):

local protected = {}
function protect(key, value)
    if _G[key] then
        protected[key] = _G[key]
        _G[key] = nil
    else
        protected[key] = value
    end
end

local meta = {
    __index = protected,
    __newindex = function(tbl, key, value)
        if protected[key] then
            error("attempting to overwrite constant " .. tostring(key) .. " to " .. tostring(value), 2)
        end
        rawset(tbl, key, value)
    end
}

setmetatable(_G, meta)

-- sample usage
GLOBAL_A = 10
protect("GLOBAL_A")

GLOBAL_A = 5
print(GLOBAL_A)

Tags:

Constants

Lua