首页 > 解决方案 > 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

标签: luascopeconstantslocal-variables

解决方案


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


推荐阅读