[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: reading a .json file from disc
- From: Rob Kendrick <rjek@...>
- Date: Fri, 15 Jul 2011 16:08:17 +0100
On Fri, Jul 15, 2011 at 11:00:49AM -0400, Dave Collins wrote:
> I'm doing something wrong.
>
> (I am converting an api call into a local file call. It should just read the entire 70K response (in json format) into the var. I parse it out later.)
>
> This hangs my app:
>
> function file_getdata()
> local data_file_path = gre.SCRIPT_ROOT .. "/myfile.json"
> local f = io.open(data_file_path)
> f = io.read("*all")
> f = io.close()
> return f
> end
Several points:
1) You're not checking if io.open() succeeds. Wrap it in assert or
otherwise handle the problem:
local f = assert(io.open(data_file_path, "r"))
2) You're using io.read() incorrectly: it expects a file handle as its
first parameter. Also, you can just use a method call:
f = f:read "*a"
3) You've not lost the file handle, because you've over-written it with
what you read from the file.
4) io.close() expects a file handle to close, or you can use the method
call as above.
5) You assign the return value of io.close() (which will be failing
anyway) to your f variable, losing the string you read.
I would rewrite as:
function file_getdata(location, filename)
local path = (location or gre.SCRIPT_ROOT) .. "/" .. (filename or "myfile.json")
local f = assert(io.open(path, "r"))
local c = f:read "*a"
f:close()
return c
end
B.