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

error handling mishap.

Started by cmdpwnd, 18 March 2016 - 02:39 AM
cmdpwnd #1
Posted 18 March 2016 - 03:39 AM
Hey guys, so I've been working on a networked key card access system [ worked perfectly until I tried to do what this question is about.. cheers :)/> ] and I'm attempting to do error catching on a file handle. When i first implemented a pcall() it returned false and I thought how could that be if two seconds earlier I had run the code without pcall and the file handle worked flawlessly? (file closing: successful) So now I've been trying to dig around and figure out why this has happened and am simply printing basic info to the screen. the error reads:


startup:147: attempt to call table

Which is the line of the pcall itself. I'm quite stumbled on this. The physical setup for this is as follows:



Also here is the source code
EDIT: Line 136: 'cmdpwnd' should read 'cdunn' sorry :)/>


http://pastebin.com/9hQJvzd1

username is the floppy's label (see picture: cdunn). password is as follows:


{
  authentication = 'password'
}

Any and all help is appreciated. Thanks

ANSWER

--[[
the file is a table. pcall cannot call on tables so.. 
encapsulate it in a dummy wrapper function
--]]
local ok, err = pcall(function() return fs.open(mount.."/dc","r") end)
credit: Dragon53535
Edited on 18 March 2016 - 03:07 AM
Dragon53535 #2
Posted 18 March 2016 - 04:00 AM
Like the error says, you cannot call a table. Which is all a file handle is. If you want to check for errors then create a dummy function for it.

pcall is protected call, in which it will catch the errors without fully closing your script. Your big problem here lies because you passed a table (the return value for fs.open) and it cannot call a table like a function.


local tbl = {}
tbl()
Same error, just different code.

Fix:

local ok, err = pcall(function() return fs.open(mount.."/dc","r") end)

That bit of code

function() ... end
with the … being your code, is just a small dummy function, what in essence that line does is create a function pointer in memory that does exactly what I've typed out, and passes that as an argument into pcall, which since it's a function is able to be called correctly. I used return on the fs.open since you still need that file handle to use.
Edited on 18 March 2016 - 03:04 AM
cmdpwnd #3
Posted 18 March 2016 - 04:04 AM
wow, thanks! :)/>
Dragon53535 #4
Posted 18 March 2016 - 04:06 AM
Quick note, err is going to be set to your file handle, which means that it will already be open to be read by the time line 151 comes up. just remove that line and change 152 and 153 to reference err instead of f1.