Lua语言入门 - Lua常量

在Lua中,虽然没有直接的常量关键字(如C++中的`const`),但你可以通过一些编程技巧和约定来实现类似常量的行为。以下是几种常见的方法:

1. 使用全局变量并命名规范

你可以定义一个全局变量,并通过命名约定来表示它是一个常量。例如,使用全大写字母来命名常量。

复制代码
```lua
MY_CONSTANT = 42

print(MY_CONSTANT)  -- 输出: 42
```

虽然这种方法不能防止变量被修改,但通过命名约定可以提醒开发者不要修改这些值。

2. 使用元表(Metatable)

你可以使用元表来控制对表的访问,从而模拟常量行为。

复制代码
local constants = {};
setmetatable(constants, {
    __newindex = function(t, key, value)
        error("Attempt to modify a constant value")
    end
})

constants.PI = 3.14159;

print(constants.PI)  -- 输出: 3.14159

-- 尝试修改常量会引发错误

复制代码
lua: const.lua:4: Attempt to modify a constant value
stack traceback:
	[C]: in function 'error'
	const.lua:4: in function <const.lua:3>
	const.lua:8: in main chunk
	[C]: ?

3. 使用模块和私有变量

你可以将常量放在一个模块中,并使用局部变量来存储它们,这样外部代码无法直接访问这些变量。```lua

复制代码
-- constants.lua
local M = {}
local privateConstants = {
    PI = 3.14159,
    E = 2.71828
}

function M.getPI()
    return privateConstants.PI
end

function M.getE()
    return privateConstants.E
end

return M

```

然后在其他文件中使用这个模块:

```lua

复制代码
local constants = require("constants")

print(constants.getPI())  -- 输出: 3.14159
print(constants.getE())   -- 输出: 2.71828

```

4. 使用只读属性(Read-Only Property)

如果你使用的是Lua 5.3或更高版本,可以使用`__index`元方法来实现只读属性。

```lua

复制代码
local constants = setmetatable({}, {
    __index = function(t, key)
        if key == "PI" then
            return 3.14159
        elseif key == "E" then
            return 2.71828
        else
            error("Invalid constant name")
        end
    end,
    __newindex = function(t, key, value)
        error("Attempt to modify a constant value")
    end
})

print(constants.PI)  -- 输出: 3.14159
print(constants.E)   -- 输出: 2.71828

-- 尝试修改常量会引发错误

constants.PI = 3.14 -- 报错: Attempt to modify a constant value

```

5.函数+表

复制代码
function Supermarket()
	local tabDefinition =
	{
		Candy = 1;
		Cookie = 2;
		Jelly = 3;
	};

	return tabDefinition;
end

print("Candy", Supermarket().Candy);
print("Cookie", Supermarket().Cookie);
print("Jelly", Supermarket().Jelly);
Supermarket().Jelly = 5;
print("Candy", Supermarket().Candy);
相关推荐
梦梦代码精7 小时前
电商系统不是技术堆叠:LikeShop如何用分层Hold住复杂业务?
java·docker·代码规范
凯瑟琳.奥古斯特7 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
负责的蛋挞7 小时前
异步HttpModule的实现方式
java·服务器·前端
AC赳赳老秦7 小时前
防火墙规则批量配置实战:OpenClaw 自动生成模板、批量下发与合规性校验全解析
java·开发语言·人工智能·python·github·php·openclaw
☆cwlulu8 小时前
调试排查工具介绍(gdb、strace、Valgrind等)
开发语言·c++·嵌入式硬件·ubuntu
Tian_Hang8 小时前
Eclipse Ditto 物模型相关代码
java·运维·服务器·ide·eureka·eclipse
C语言小火车8 小时前
C++ 快速排序(Quick Sort)深度精讲:分治思想、Lomuto 分区法及三数取中优化,面试手撕必会
c语言·开发语言·c++·面试·排序算法·快速排序
sycmancia8 小时前
Qt——多线程间的互斥
开发语言·qt
一知半解仙8 小时前
2026年彻底免费的辅助编程Agent大模型汇总
开发语言·人工智能·开源
Mr-Wanter8 小时前
wsl2 jdk管理工具之sdkman
java·开发语言·sdkman