lua-users home
lua-l archive

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

On Tue, Jun 14, 2011 at 9:49 AM, Han Zhao <> 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 =, 'rb')
   if not f then
     return nil, 'file not found: ' .. path
   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
       if ((linecount % nlines) == 0) then
         callback(f:seek('cur') / length)
     return nil

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))

Of course, if your app data file is not split up into lines, this may
need to be adjusted a bit...