lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Thanks. Documentation seems to be terse i.e. without examples.

Dave Collins
Front-End Engineer
Mercatus Technologies Inc.
60 Adelaide Street East, Suite 700
Toronto ON M5C 3E4
T  416 603 3406 x 298
F  416 603 1790

dave.collins@mercatustechnologies.com
www.mercatustechnologies.com


-----Original Message-----
From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On Behalf Of Rob Kendrick
Sent: Friday, July 15, 2011 11:08 AM
To: Lua mailing list
Subject: Re: reading a .json file from disc

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.