lua5.2文档

本文详细介绍了Lua中模块管理的基本设施,包括如何使用require函数加载模块,以及dofile和loadfile函数的作用和区别。此外,文章还讨论了部分Lua 5.2的变化,如模块管理的废弃和相关函数的移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块管理:
The package library provides basic facilities for loading modules in Lua. It exports one function directly in the global environment: require. Everything else is exported in a table package.

require (modname)
require returns the value stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module.


module (name [, ···])
Creates a module. If there is a table in package.loaded[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,

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.

package.seeall (module)
Sets a metatable for module with its __index field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function module.

摘自:http://blog.163.com/hbu_lijian/blog/static/126129153201422902256778/
1.dofile与loadfile
dofile当作Lua运行代码的chunk的一种原始的操作。dofile实际上是一个辅助的函数。真正完成功能的函数是loadfile;与dofile不同的是loadfile编译代码成中间码并且返回编译后的chunk作为一个函数,而不执行代码;另外loadfile不会抛出错误信息而是返回错误代。我们可以这样定义dofile:
function dofile (filename)
local f = assert(loadfile(filename))
return f()
end

如果loadfile失败assert会抛出错误。loadfile更加灵活。在发生错误的情况下,loadfile返回nil和错误信息,这样我们就可以自定义错误处理。另外,如果我们运行一个文件多次的话,loadfile只需要编译一次,但可多次运行。dofile却每次都要编译。

loadstring (string [, chunkname])
Similar to load, but gets the chunk from the given string.
To load and run a given string, use the idiom
assert(loadstring(s))()
When absent, chunkname defaults to the given string.


Lua5.2:部分变化:
Function module is deprecated. It is easy to set up a module with regular Lua code.
Functions setfenv and getfenv were removed, because of the changes in environments.
增加 bit32模块
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值