是否有类似const的关键字或其他在lua中与此关键字相同的关键字?

问题描述 投票:23回答:4

lua中有const关键字吗?还是其他类似的东西?因为我想将变量定义为const并防止更改变量的值。预先感谢。

lua const
4个回答
16
投票

Lua不会not自动支持常量,但是您可以添加该功能。例如,通过将常量放在表中,然后使用metatable将表设为只读。

这里是操作方法:http://andrejs-cainikovs.blogspot.se/2009/05/lua-constants.html

复杂之处在于,常量的名称不仅是“ A”和“ B”,还包括“ CONSTANTS.A”和“ CONSTANTS.B”之类的名称。您可以决定将所有常量放在一个表中,或者将它们按逻辑分组到多个表中。例如用于数学常数的“ MATH.E”和“ MATH.PI”,等等。


4
投票

如前所述,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)

-- sample usage
GLOBAL_A = 10
protect("GLOBAL_A")

GLOBAL_A = 5
print(GLOBAL_A)

2
投票

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

最简单的解决方案是在注释中写一个大的警告,告知它禁止写入此变量...

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

类似这样的东西:

local readonly_vars = { foo=1, bar=1, baz=1 }
setmetatable(_G, {__newindex=function(t, k, v)
  assert(not readonly_vars[k], 'read only variable!')
  rawset(t, k, v)
end})

然后,如果您尝试向foo分配某些内容,则会引发错误。


2
投票

我知道这个问题已经七岁了,但是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/work/doc/manual.html#3.3.7

© www.soinside.com 2019 - 2024. All rights reserved.