Asynchronous IO API
The async IO API lets Lua read and write large files without locking up the game. This can be particularly useful for reading or writing lots of small files, where the delay from the OS opening each one can be very significant.
Note: When a callback is run, it's only ever called between two frames. Thus if you try loading a thousand files one at a time (each time one callback completes, starting the next read) then it will take at least a thousand frames, even if the actual IO operations are much faster than that.
Note: On Windows, automatic newline conversion is disabled so it's safe to read and write binary data. This
is the same as supplying
b as an option to
Note: The error messages returned may vary between Windows and Linux.
Async file read
function void blt.async_io.read(path, function(data, err))
Reads the contents of a file, then calls the given callback function when the read is complete.
If the read completed successfully, the callback is invoked with a single argument, that being the string representation of the file contents.
If an error occurred, the callback is invoked with two arguments: first nil and then a string with the error message.
blt.async_io.read("mods/testing/test.lua", function(data, err) log("Read data async (valid): " .. tostring(data) .. ":" .. tostring(err)) end) blt.async_io.read("mods/testing/this file does not exist", function(data, err) log("Read data async (invalid): " .. tostring(data) .. ":" .. tostring(err)) end)
Will print (not necessarily in this order):
Read data async (valid): <contents of the file goes here>:nil Read data async (invalid): nil:No such file or directory
Async file write
function void blt.async_io.write(path, data, function(status, err))
Asynchronously writes the given data to a file. If the file already exists, it is overwritten.
If the call was successful, the callback runs with a single argument:
If the call failed, the callback runs with
false as the first argument and the error message from the OS as
the second one.
blt.async_io.write("mods/testing/my-test-output-file.txt", "Hello, World", function(status, err) if not status then log("Failed to write file " .. path .. " : " .. tostring(err)) end end)