Do the const and close keywords in Lua actually do anything?

Viewed 1677

I was excited to learn that, as of Lua 5.4, Lua supports constant (const) and to-be-closed (close) variables! However, upon testing these keywords, they don't seem to do anything at all. I wrote the following code to sample the features to get a better grasp of their exact usage:

function f()
  local const x = 3
  print(x)
  x = 2
  print(x)
end

f()

function g()
  local close x = {}
  setmetatable(x, {__close = function() print("closed!") end})
end

g()

I titled the file constCheck.lua and ran it with lua constCheck.lua. The output is as follows:

3
2

I was expecting an error on my call to f(), or at least for it to print 3 twice, instead it seemed to reassign x with no issue at all. Further, I was expecting the call to g() to print out "closed!" when x left scope at the end of the function, but this did not happen. I can't find very many examples of these keywords' usage. Am I using them properly? Do they work?

Note: lua -v => Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio

2 Answers

From the Lua 5.4 Reference Manual : 3.3.7 - Local Declarations

Each variable name may be postfixed by an attribute ( a name between angle brackets):

attrib ::= [‘<’ Name ‘>’]

There are two possible attributes: const, which declares a constant variable, that is, a variable that cannot be assigned to after its initialization; and close, which declares a to-be-closed variable

So you would have to write local x <const> = 3 for example.

Your code local const x = 3 is equivalent to

local const = nil
x = 3

So you're actually creating a local nil value const and a global number value x.

Related