Lua中module函数的作用和用法

12 篇文章 0 订阅

前言:我做的第一个cocos Lua项目中,对module函数没有任何印象;换了家公司做第二个cocos Lua项目时,有一句话:module("common.res", package.seeall)引起了我的注意。由于第一个项目没用过module函数总结出这个函数应该是可用可不用性质,通过官网5.1参考手册可以查到官方对module的解释:

module (name [, ···])

Creates a module. If there is a table in package.loaded[name], this table is the module. Otherwise, if there is a global table t with the given name, this table is the module. Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name]. This function also initializes t._NAMEwith the given name, t._M with the module (t itself), and t._PACKAGE with the package name (the full module name minus last component; see below). Finally, module sets t as the new environment of the current function and the new value of package.loaded[name], so that require returns t.

If name is a compound name (that is, one with components separated by dots), module creates (or reuses, if they already exist) tables for each component. For instance, if name is a.b.c, then module stores the module table in field c of field b of global a.

This function can receive optional options after the module name, where each option is a function to be applied over the module.

我的翻译和理解(自信英文水平过关):module函数创建一个全局模块(table变量)。如果以name命名的全局table已存在,则进行覆盖。否则创建以name命名的全局table。如果参数name是合成名字比如a.b.c,则创建一个全局table a,可通过a.b.c找到table c。module的第二个参数是控制在module函数所在文件中之前环境是否被覆盖的作用,不传第二个参数的话,在module函数所在文件中:之前环境丢失,比如无法找到print函数。传 package.seeall的话,保留之前环境。

module使用测试代码:

--moduleTest1.lua
module("a.b.c", package.seeall)
print("in moduleTest1")
time = "10:15"
local weekday = "Monday"

--moduleTest2.lua
module("a.b.c", package.seeall)
print("in moduleTest2")
time = "20:15"

--moduleTest3.lua
module("module3")
print("in moduleTest3")
time = "10:15"

--main.lua
print("----------------------")
require("game.moduleTest1")     -- 输出:  in moduleTest1
print(a.b.c.time)               -- 输出:  10:15   成功访问module中全局变量
print(a.b.c.weekday)            -- 输出:  nil     无法访问module中local变量
print("----------------------")
require("game.moduleTest2")     -- 输出:  in moduleTest2
print(a.b.c.time)               -- 输出:  20:15   成功访问a.b.c被重新赋值的time
print("----------------------")
require("game.moduleTest3")     -- 输出:  attemp to call global print(a nil value)

总结:

1.module函数作用:创建全局模块(全局table变量)

2.module文件中定义的local 变量在外部无法访问

3.module第二个参数package.seeall的作用:只有传package.seeall时,在module函数所在文件中,才能访问全局环境中的变量

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ellis1970

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值