Lua语言入门 - Lua常量

打印 上一主题 下一主题

主题 996|帖子 996|积分 2988

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在Lua中,固然没有直接的常量关键字(如C++中的`const`),但你可以通过一些编程技巧和约定来实现类似常量的行为。以下是几种常见的方法:
 1. 使用全局变量并定名规范


你可以界说一个全局变量,并通过定名约定来表示它是一个常量。比方,使用全大写字母来定名常量。
  1. ```lua
  2. MY_CONSTANT = 42
  3. print(MY_CONSTANT)  -- 输出: 42
  4. ```
复制代码
固然这种方法不能防止变量被修改,但通过定名约定可以提示开发者不要修改这些值。

 2. 使用元表(Metatable)


你可以使用元表来控制对表的访问,从而模拟常量行为。
  1. local constants = {};
  2. setmetatable(constants, {
  3.     __newindex = function(t, key, value)
  4.         error("Attempt to modify a constant value")
  5.     end
  6. })
  7. constants.PI = 3.14159;
  8. print(constants.PI)  -- 输出: 3.14159
复制代码
-- 实验修改常量会引发错误

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

3. 使用模块和私有变量


你可以将常量放在一个模块中,并使用局部变量来存储它们,如许外部代码无法直接访问这些变量。```lua
  1. -- constants.lua
  2. local M = {}
  3. local privateConstants = {
  4.     PI = 3.14159,
  5.     E = 2.71828
  6. }
  7. function M.getPI()
  8.     return privateConstants.PI
  9. end
  10. function M.getE()
  11.     return privateConstants.E
  12. end
  13. return M
复制代码
```
然后在其他文件中使用这个模块:
```lua
  1. local constants = require("constants")
  2. print(constants.getPI())  -- 输出: 3.14159
  3. print(constants.getE())   -- 输出: 2.71828
复制代码
```
4. 使用只读属性(Read-Only Property)

如果你使用的是Lua 5.3或更高版本,可以使用`__index`元方法来实现只读属性。
```lua
  1. local constants = setmetatable({}, {
  2.     __index = function(t, key)
  3.         if key == "PI" then
  4.             return 3.14159
  5.         elseif key == "E" then
  6.             return 2.71828
  7.         else
  8.             error("Invalid constant name")
  9.         end
  10.     end,
  11.     __newindex = function(t, key, value)
  12.         error("Attempt to modify a constant value")
  13.     end
  14. })
  15. print(constants.PI)  -- 输出: 3.14159
  16. print(constants.E)   -- 输出: 2.71828
复制代码
-- 实验修改常量会引发错误
constants.PI = 3.14  -- 报错: Attempt to modify a constant value
```
 

5.函数+表

  1. function Supermarket()
  2.         local tabDefinition =
  3.         {
  4.                 Candy = 1;
  5.                 Cookie = 2;
  6.                 Jelly = 3;
  7.         };
  8.         return tabDefinition;
  9. end
  10. print("Candy", Supermarket().Candy);
  11. print("Cookie", Supermarket().Cookie);
  12. print("Jelly", Supermarket().Jelly);
  13. Supermarket().Jelly = 5;
  14. print("Candy", Supermarket().Candy);
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

忿忿的泥巴坨

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表