48

Is there a const keyword in lua ? Or any other similar thing? Because i want to define my variables as const and prevent change of the value of the variables. Thanks in advance.

4 Answers 4

52

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.

1
  • 5
    Important to note: The error will be produced at "compile" time (when the code is loaded and evaluated), not at runtime!
    – BotOfWar
    Jun 30, 2020 at 10:48
24

Update: November 2023

Following the release of Lua 5.4 in June 2020, support for constant variables has been added, refer to this answer by Ainar-G for more more information.


Original Answer

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.

2
  • 5
    See also lua-users.org/wiki/ReadOnlyTables. And note that you can set _ENV and/or _G to a read-only table to simulate global constants (at some cost in performance.)
    – finnw
    Sep 11, 2012 at 11:44
  • 2
    This seems like a very important note from the link posted by @finnw: "Furthermore, this method of creating read-only tables interferes with pairs, ipairs, next, the # operator, and other forms of table iteration."
    – chris
    Oct 14, 2015 at 22:42
5

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)
2

There is no const keyword in Lua or similar construct.

The easiest solution is to write a big caution in a comment, telling that it is forbidden to write to this variable...

It is however technically possible to forbid writing (or reading) to a global variable by providing a metatable to the global environment _G (or _ENV in Lua 5.2).

Something like this:

local readonly_vars = { foo=1, bar=1, baz=1 }
setmetatable(_G, {__newindex=function(t, k, v)
  assert(not readonly_vars[k], 'read only variable!')
  rawset(t, k, v)
end})

Then if you try to assign something to foo, an error is thrown.

1
  • This code is incorrect. It will protect against setting NEW variables, but not changing them.
    – ZzZombo
    Oct 8, 2016 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.