写男主重生做网站的小说,个人网页设计尺寸是多少,宁波网站建设 熊掌号,百度竞价开户哪家好Lua 基础相关知识 第四期
require
模块#xff0c;通常是一个表#xff0c;表里存储了一些字段和函数#xff0c;单独写在一个 lua 文件。
例如#xff0c;这是一个 tools.lua 文件#xff0c;定义了一个局部 tools 表#xff0c;包含一个 log 函数#xff0c;可以传…Lua 基础相关知识 第四期
require
模块通常是一个表表里存储了一些字段和函数单独写在一个 lua 文件。
例如这是一个 tools.lua 文件定义了一个局部 tools 表包含一个 log 函数可以传入标题和信息函数内部格式化字符串输出。
最后要 return tools在 require 加载这个模块时才能拿到返回的 tools 表。
local tools {}tools.log function (title, message)print(string.format([%s] %s, title, message))
endreturn tools在其他 lua 文件中加载这个 tools 模块进行使用。
local tools require tools
tools.log(console, hello lua)-- [console] hello lua标准库也可以通过 require 加载换个名称。
local m require math
local n m.abs(-1)
print(n)-- 1require 会做已加载的检查如果已经加载过一个模块了就不会再重复加载了。
如果要移除原来加载的模块可以把模块从 package.loaded 中删除。
package.loaded.tools nilloadfile dofile require
这三个函数都是用来加载和执行外部 lua 脚本的不过有一些区别
loadfile 加载编译指定的 lua 文件但不执行文件中的代码需要手动调用返回值是一个函数dofile 加载编译并执行指定的 lua 文件返回值是文件中最后一个表达式的值require 先检查 package.loaded 是否已加载模块若已加载则直接返回若不存在则编译执行一次并记录到 package.loaded返回值通常是一个表
这里所说的执行是指被加载的 lua 文件中写在表外面可以被执行的语句例如在 tools 中添加一行打印表示欢迎使用这个模块。
local tools {}print(Welcome to use this tools module!)tools.log function (title, message)print(string.format([%s] %s, title, message))
endreturn tools先尝试使用 loadfile注意第一行代码加载的是 tools.lua需要增加 .lua 后缀名第一行并没有输出。
第二行代码打印了 loadfile 的返回值输出的是一个 function。
第三行代码手动调用了返回的函数才执行了 tools.lua 里面的一行打印。
local tools loadfile(tools.lua)
print(tools) -- function: 0000025E2F7791D0
tools() -- Welcome to use this tools module!再尝试一下 dofile同样的第一行代码加载的是 tools.lua第一行就输出了。
第二行代码打印的返回值是 table也就是 tools.lua 最后一行的 return tools。
第三行代码则不是直接调用 tools 了因为它并不是一个函数。应该调用 tools.log。
local tools dofile(tools.lua) -- Welcome to use this tools module!
print(tools) -- table: 00000150C5D61D30
tools.log(console, hello lua) -- [console] hello lua最后回到 require注意第一行代码没有 .lua 后缀名第一行就输出了。
后面两行代码和 dofile 是一致的。
local tools require(tools) -- Welcome to use this tools module!
print(tools) -- table: 0000025D08BF13D0
tools.log(console, hello lua) -- [console] hello lua如果再次加载 lua 文件loadfile 依然是需要手动调用dofile 会再次输出require 则只输出一次除非移除已加载的模块。
local tools_loadfile loadfile(tools.lua)
local tools_loadfile loadfile(tools.lua)local tools_dofile dofile(tools.lua) -- Welcome to use this tools module!
local tools_dofile dofile(tools.lua) -- Welcome to use this tools module!local tools_require require(tools) -- Welcome to use this tools module!
local tools_require require(tools)package.loaded.tools nil
local tools_require require(tools) -- Welcome to use this tools module!