Using Lua, check if the file is a directory

If i have this code

local f = io.open("../web/", "r") print(io.type(f)) -- output: file 

how can i find out if f points to a directory?

+5
source share
7 answers

Lua libraries cannot determine this by default.

However, you can use the third-party LuaFileSystem library to access more complex file system interactions; he is also cross-platform.

LuaFileSystem provides lfs.attributes that you can use to request file mode:

 require "lfs" function is_dir(path) -- lfs.attributes will error on a filename ending in '/' return path:sub(-1) == "/" or lfs.attributes(path, "mode") == "directory" end 
+5
source

ANSI C does not indicate any way to obtain directory information, so vanilla Lua cannot tell you this information (since Lua is committed to 100 percent portability). However, you can use an external library such as LuaFileSystem to identify directories.

Programming in Lua even explicitly indicates the missing functionality of the directory:

As a more complex example, we write a function that returns the contents of a given directory. Lua does not provide this function in its standard libraries because ANSI C does not have functions for this task.

This example moves to show you how to write a dir function in C yourself.

+9
source

I found this piece of code in the library that I am using:

 function is_dir(path) local f = io.open(path, "r") local ok, err, code = f:read(1) f:close() return code == 21 end 

I don’t know what the code will be on Windows, but on Linux / BSD / OSX it works fine.

+6
source

if you do

 local x,err=f:read(1) 

then you will get "Is a directory" in err .

+5
source

At least for UNIX:

 if os.execute("cd '" .. f .. "'") then print("Is a dir") else print("Not a dir") end 

:)

+2
source
 function fs.isDir ( file ) if file == nil then return true end if fs.exists(file) then os.execute("dir \""..userPath..file.."\" >> "..userPath.."\\Temp\\$temp") file = io.open(userPath.."\\Temp\\$temp","r") result = false for line in file:lines() do if string.find(line, "<DIR>") ~= nil then result = true break end end file:close() fs.delete("\\Temp\\$temp") if not (result == true or result == false) then return "Error" else return result end else return false end end 

This is the code I extracted from the library I found earlier.

0
source

This is first checked if the path can be read (which is also nil for empty files), and then checks that the size is not 0.

 function is_dir(path) f = io.open(path) return not f:read(0) and f:seek("end") ~= 0 end 
0
source

Source: https://habr.com/ru/post/1309762/


All Articles