Reputation: 5925
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.
Upvotes: 54
Views: 45651
Reputation: 2214
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.
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.
Upvotes: 25
Reputation: 36199
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.
Upvotes: 64
Reputation: 663
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)
Upvotes: 5
Reputation: 6858
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.
Upvotes: 2