async_event.lua 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. local tbl = engine or minetest
  2. tbl.async_jobs = {}
  3. if engine ~= nil then
  4. function tbl.async_event_handler(jobid, serialized_retval)
  5. local retval = nil
  6. if serialized_retval ~= "ERROR" then
  7. retval= marshal.decode(serialized_retval)
  8. else
  9. tbl.log("error","Error fetching async result")
  10. end
  11. assert(type(tbl.async_jobs[jobid]) == "function")
  12. tbl.async_jobs[jobid](retval)
  13. tbl.async_jobs[jobid] = nil
  14. end
  15. else
  16. minetest.register_globalstep(
  17. function(dtime)
  18. local list = tbl.get_finished_jobs()
  19. for i=1,#list,1 do
  20. local retval = marshal.decode(list[i].retval)
  21. assert(type(tbl.async_jobs[jobid]) == "function")
  22. tbl.async_jobs[list[i].jobid](retval)
  23. tbl.async_jobs[list[i].jobid] = nil
  24. end
  25. end)
  26. end
  27. function tbl.handle_async(fct, parameters, callback)
  28. --serialize fct
  29. local serialized_fct = marshal.encode(fct)
  30. assert(marshal.decode(serialized_fct) ~= nil)
  31. --serialize parameters
  32. local serialized_params = marshal.encode(parameters)
  33. if serialized_fct == nil or
  34. serialized_params == nil or
  35. serialized_fct:len() == 0 or
  36. serialized_params:len() == 0 then
  37. return false
  38. end
  39. local jobid = tbl.do_async_callback( serialized_fct,
  40. serialized_fct:len(),
  41. serialized_params,
  42. serialized_params:len())
  43. tbl.async_jobs[jobid] = callback
  44. return true
  45. end