[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: loadfile callback?
- From: Duncan Cross <duncan.cross@...>
- Date: Tue, 14 Jun 2011 10:59:02 +0100
On Tue, Jun 14, 2011 at 9:49 AM, Han Zhao <abrash_han@hotmail.com> wrote:
> hi,
>
> I'm using lua table to store my app data and load the data
> back via loadfile().
>
> When the table is big, I'd like a callback in loadfile() to
> display some progress info in the UI.
>
> Is it possible?
>
> Best Regards,
> hz
>
>
>
Not with loadfile() itself, but if you pass a custom coroutine-based
loader function to load() it's quite possible, something like this:
-- variation on loadfile() that calls [callback] every [nlines] lines
function loadfile_callback(path, nlines, callback)
local f = io.open(path, 'rb')
if not f then
return nil, 'file not found: ' .. path
end
return load(coroutine.wrap(function()
-- get the total length of the file in bytes
local length = f:seek('end')
f:seek('set', 0)
local linecount = 0
for line in f:lines() do
linecount = linecount + 1
coroutine.yield(line)
if ((linecount % nlines) == 0) then
callback(f:seek('cur') / length)
end
end
return nil
end))
end
An example of using this to display the percentage loaded from a file
every 1000 lines:
local chunk = assert(loadfile_callback('largefile.lua', 1000, function(ratio)
print(string.format('%d%% complete...', ratio * 100))
end))
Of course, if your app data file is not split up into lines, this may
need to be adjusted a bit...
-Duncan