kikito/inspect.lua

Error when inspecting table returned by luaposix.dir

theGreatWhiteShark opened this issue · 3 comments

When applying inspect to a table returned by the dir function of the luaposix package an error is thrown.

posix = require 'posix'
inspect( posix.dir( posix.getenv()[ "HOME" ] ) )

I'm not a hundred percent sure if this error is reproducible since it could depend on the content of my home folder. If necessary I will do a more thorough search.

I tried this out, and the error is because posix.dir returns two values: a table (list of entries in the directory) and a number (the number of entries). inspect expects a table of options if it receives a second argument, but receives a number. It tries to index the number, which doesn't work (unless numbers have been given an __index metamethod).

Removing the second return value by adding an extra set of parentheses fixes the problem:

dir = inspect((posix.dir(posix.getenv()["HOME"]))

The multiple return values can be truncated to the first value by enclosing the expression in parentheses.

inspect( ( posix.dir( posix.getenv()[ "HOME" ] ) ) )

See also https://www.luafaq.org/gotchas.html#T8.1

In addition of enclosing the parameters into extra parenthesis, you can enclose them into a table, as mentioned in #46:

inspect( { posix.dir( posix.getenv()[ "HOME" ] ) } )

Or even (abusing Lua's syntax a bit):

inspect{ posix.dir( posix.getenv()[ "HOME" ] ) }