Lua基础:文件加载,错误处理

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

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

dofile函数:

  1. function dofile (filename) 
  2. local f = assert(loadfile(filename)) 
  3. return f() 
  4. end

require函数:Lua 提供高级的 require 函数来加载运行库。

1. require 会搜索目录加载文件
2. require 会判断是否文件已经加载避免重复加载同一文件。

  1. local file,msg
  2. repeat
  3.     print "enter a file name:"
  4.     local name=io.read()
  5.     if not name then return end
  6.     file,msg=io.open(name,"r")         --使用io.open()打开一个文件
  7.     if not file then print(msg) end
  8. until file

错误:

  1. print "enter a number:"
  2. n = io.read("*number") 
  3. if not n then error("invalid input") end  --error()函数抛出错误,参数是错误信息
  4. -----------------------------------------------------------------------------------------------------------
  5. local status, err = pcall(function () error({code=121}) end) 
  6. print(err.code)                                   --> 121 
  7. ---------------------------------------------------------------------------------------------
  8. print(debug.traceback())                 --获取运行时的traceback信息

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值