Lua iterator that fails?

I have a very simple problem with a simple iterator.

Let's say that I create a function files()that iterates through all the files in a folder:

for file in files("/path/to/folder") do
  print(file)
end

Now this seems perfect, but there is a problem: what if the folder does not exist or we do not have read permissions?

How will we indicate such an error?

One solution would be to have files()return nil, "no read permission"in this case. Then we could make a call files()inside assert():

for file in assert(files("/path/to/folder")) do
  print(file)
end

, , . assert(). , ? , files() , . Lua - files() - nil, ( " nil" ).

,

, files(), , , , ?

, ?

+4
2

-: , nil +, files ( error). , assert, " ".

files, - (function() end) error .

:

-- an iterator that immediately stops a for loop
local function dummy_iter() end

-- catch errors and skip for loop in that case
function iterpcall( g, ... )
  local ok, f, st, var = pcall( g, ... )
  if ok then
    return f, st, var
  else
    return dummy_iter
  end
end


for file in iterpcall( files, "/path/to/folder" ) do
  print( file )
  for line in iterpcall( io.lines, file ) do -- works for other iterators as well
    print( line )
  end
end

iterpcall , (files io.lines), (f). f pcall, .

+7

, , (, ). .

2 ( ).

-- raise error
for file in files(...) do ... end

-- return error
files(...,function(file) ... end)

2 .

+3

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


All Articles