dofile函数:
- function dofile (filename)
- local f = assert(loadfile(filename))
- return f()
- end
require函数:Lua 提供高级的 require 函数来加载运行库。
1. require 会搜索目录加载文件
2. require 会判断是否文件已经加载避免重复加载同一文件。
- local file,msg
- repeat
- print "enter a file name:"
- local name=io.read()
- if not name then return end
- file,msg=io.open(name,"r") --使用io.open()打开一个文件
- if not file then print(msg) end
- until file
错误:
- print "enter a number:"
- n = io.read("*number")
- if not n then error("invalid input") end --error()函数抛出错误,参数是错误信息
- -----------------------------------------------------------------------------------------------------------
- local status, err = pcall(function () error({code=121}) end)
- print(err.code) --> 121
- ---------------------------------------------------------------------------------------------
- print(debug.traceback()) --获取运行时的traceback信息

本文深入探讨了Lua语言中dofile和require函数的使用方法,包括文件加载、错误处理及调试技巧。通过具体示例,展示了如何利用这些函数进行模块加载,并介绍了Lua中error和pcall函数的作用,以及debug.traceback的使用,帮助读者掌握Lua编程的核心技巧。
1635

被折叠的 条评论
为什么被折叠?



