Refactor blocking I/O in Lua using coroutines

Viewed 351

Say I have the following Lua code, which reads and parses data from a file.

local cjson = require 'cjson'

function read_data (path)
  local file = io.open(path, 'r')
  local raw = file.read('*all')
  return cjson.decode(raw)
end

function use_data (path)
  local data = read_data(path)
  -- do something with `data`
end

I'm now trying to figure out what the non-blocking version of this basic example would look like.

In Javascript, you'd make both of those functions asynchronous, and then await the results. But judging by what I've read so far about Lua, here I'd only have to refactor the read_data function to use coroutines, and I could leave the use_data code as-is. How would I achieve this?

EDIT: Solutions that replace the current calls with external libraries are welcome. Whatever it takes to make the example non-blocking, basically.

0 Answers
Related