This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
CharlesBroughton's profile picture

[Lua][Error] attempt to index ? (a nil value) [SOLVED]

Started by CharlesBroughton, 10 August 2012 - 09:38 PM
CharlesBroughton #1
Posted 10 August 2012 - 11:38 PM
for _,file in ipairs( fs.list("/accounts") ) do
  h = fs.open( file, "r" )
  print( " - " .. file .. " : " .. h.readAll( ) )
  h.close( )
end

The issue stems on line 3 apparently, yet I don't see any obvious problems there… and LUA debugging isn't as nice as any other language and tell me the column, or the actual method causing the error… nor could I find any way to produce any sort of stack trace; so if anyone knows how to do any of these things I would be grateful.

1. Yes a folder called accounts in / exists on this computer, and has files in it.
2. The code itself, including the retarded and unexplained _,file bit is copied from another thread on this site, apparently one in which the code worked for other people.

This should produce a list as follows:

- boxxy : filecontents
- cbroughton : filecontents

Instead it does this:
http://i.imgur.com/oNlov.png

Any help would be appreciated
CharlesBroughton #2
Posted 10 August 2012 - 11:55 PM
After attempting to split the code up, I see that the actual output is:

- boxxy : read:6: attempt to index ? (a nil value)

Code is now:

for _,file in ipairs( fs.list("/accounts") ) do
  h = fs.open( file, "r" )
  write( " - " )
  write( file )
  write( " : " )
  write( h.readAll( ) ) -- error here
  print( " ; " )
  h.close( )
end
CharlesBroughton #3
Posted 10 August 2012 - 11:57 PM
Alright, nevermind. I figured it out. Turns out fs.list returns all RELATIVE paths, and fs.open doens't bother telling you when it fails to open something (guessing it returns false alone.)

Editing to solved.
MysticT #4
Posted 11 August 2012 - 12:22 AM
That's why you need to check the returned value:

local h = fs.open("someFile", "r")
if h then -- check if it's open
  print(h.readAll())
else
  print("Error opening file")
end