Lua io.type()

作者: AlbertS | 来源:发表于2016-07-27 14:20 被阅读89次

前言#

不知大家有没有这种情况,拿到一个自称是文件描述符的变量,你对他产生了怀疑,比如说你认为他根本不是个文件描述符,或者说这个文件描述符已经关闭了,而这种情况是确实存在的。假设一个文件描述符已经关闭了,然后我们再次使用时,程序就会发生错误并给出警告,相信看过之前的例子大家都见到过这种情况,那么今天这个函数就是处理这个问题,来避免程序出错的情况。

内容#


io.type()##

  • 原型:io.type (obj)
  • 解释:检测一个文件描述符obj是否有效,假如obj是一个打开的文件描述符则会返回字符串"file",如果obj是一个关闭的文件描述符则会返回字符串"closed file",而当obj是一个无效的文件描述符时则会返回结果nil

Usage##

  • 首先我们新建一个文件,将文件命名为typetest.lua然后编写如下代码:
-- 打开文件
local myfile = io.open("iotypeest.txt", "w")
if nil == myfile then
    print("open file iotypeest.txt fail")
end

print("\nafter open file:")
print("myfile handle status = "..io.type(myfile))

-- 关闭文件
myfile:close()

print("\nafter close file:")
print("myfile handle status = "..io.type(myfile))

-- 随便输入一个文件名
print("\nuse a error file:")
print("error file handle status = "..(io.type(errorfile) or "nil"))
  • 运行结果
io_type.png

总结#

  • 使用文件描述符之前最好使用io.type()检测一下描述符的有效性。
  • 注意这个函数没有描述符显示使用的方法,只能把文件描述符作为参数传递进去。

相关文章

网友评论

    本文标题:Lua io.type()

    本文链接:https://www.haomeiwen.com/subject/uiuojttx.html