在lua中是否有类似于const或其他东西的关键字可以完成相同的工作?

Lua 中是否有 const 关键字?或者类似的东西吗?因为我想把我的变量定义为 const,防止变量的值被改变。谢谢。

点赞
用户1197331
用户1197331

Lua 不支持自动常量,但你可以添加这个功能。例如,将你的常量放在一个表中,并使用元表将表设置为只读。

这是如何实现的:http://andrejs-cainikovs.blogspot.se/2009/05/lua-constants.html

复杂的是你的常量名称不仅仅是 "A" 和 "B",而是像 "CONSTANTS.A" 和 "CONSTANTS.B"。你可以决定将所有常量放在一个表中,或根据逻辑将它们分组到多个表中;例如对于数学常量,将 "MATH.E" 和 "MATH.PI" 放在一起。

2012-09-11 11:44:14
用户1008957
用户1008957

Lua 中没有 const 关键字或类似的结构。

最简单的解决方案是在注释中写大警告,告诉别人禁止写入这个变量……

然而,通过为全局环境 _G(在 Lua 5.2 中为 _ENV)提供元表,可以在技术上禁止对全局变量的写入(或读取)。

像这样:

local readonly_vars = { foo=1, bar=1, baz=1 }
setmetatable(_G, {__newindex=function(t, k, v)
  assert(not readonly_vars[k], '只读变量!')
  rawset(t, k, v)
end})

然后如果你试图将某些东西分配给 foo,一个错误将被抛出。

2012-09-11 11:47:18
用户887805
用户887805

如前所述,Lua 中没有 const

你可以使用这个小技巧来 "保护" 全局定义的变量(与受保护的表相比):

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)

-- 用法示例
GLOBAL_A = 10
protect("GLOBAL_A")

GLOBAL_A = 5
print(GLOBAL_A)
2012-09-11 12:35:45
用户1892060
用户1892060

我知道这个问题已经七年了,但是 Lua 5.4 终于为开发者带来了 const(常量)!

local a <const> = 42
a = 100500

将会产生一个错误:

lua: tmp.lua:2: attempt to assign to const variable 'a'

文档:https://www.lua.org/manual/5.4/manual.html#3.3.7

2019-10-03 18:28:26