lua - 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"))
推荐阅读
- cadence - 有没有办法让 SKILL 脚本在原理图上查找和替换零件?
- javascript - Svelte - 表单提交上的事件修饰符“一次”不起作用
- netty - 如何在同一个 TCP 连接(通道)上一次处理一个请求?
- javascript - 如何在打字稿中键入对象
- apache-kafka - 从不同的应用程序访问 globalktable 或 aglobalstore - kstream
- android - 始终使用 Jetpack Compose 在 TextField 中显示占位符和 RTL 输入
- javascript - 如何使用 Array.find() 函数编辑特定对象内的名称和年龄属性
- python - 如何通过键盘快捷键在 tkinter python 中直接输入数学方程
- json - BigQuery 中的请求正文
- arrays - GAS 筛选条件以筛选数组中在选定的单个或多个字段中具有非空白(文本)单元格的记录