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

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信息

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/88061511