46

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.

oiyio
  • 5,219
  • 4
  • 42
  • 54

4 Answers4

47

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.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119
  • 4
    Important to note: The error will be produced at "compile" time (when the code is loaded and evaluated), not at runtime! – BotOfWar Jun 30 '20 at 10:48
22

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.

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
Viliam Búr
  • 2,154
  • 17
  • 14
  • 5
    See also http://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 '12 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 '15 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)
luastoned
  • 663
  • 3
  • 4
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.

prapin
  • 6,395
  • 5
  • 26
  • 44