Lua中的const和close关键字实际上有什么作用吗?
我很高兴地了解到,从 Lua 5.4 开始,Lua 支持常量 ( const) 和要关闭的 ( close) 变量!但是,在测试这些关键字时,它们似乎根本没有做任何事情。我编写了以下代码来对功能进行采样,以更好地掌握它们的确切用法:
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()
我为文件命名constCheck.lua并使用lua constCheck.lua. 输出如下:
3
2
我期待在调用 时出现错误f(),或者至少要打印3两次,相反,它似乎重新分配x没有任何问题。此外,我期待调用g()打印出“关闭!” 当x在函数结束时离开作用域时,但这并没有发生。我找不到很多关于这些关键字用法的例子。我是否正确使用它们?做他们的工作?
笔记: lua -v => Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio
回答
这<const>不是const,<close>也不是close
见https://lwn.net/Articles/826134/
do
local x <const> = 42
x = x+1
end
-- ERROR: attempt to assign to const variable 'x'
还有一些例子https://github.com/lua/lua/blob/master/testes/code.lua#L11
local k0aux <const> = 0
https://github.com/lua/lua/blob/master/testes/files.lua#L128
local f <close> = assert(io.open(file, "w"))