前言:我做的第一个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._NAME
with 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函数所在文件中,才能访问全局环境中的变量