summaryrefslogtreecommitdiff
path: root/builtin/common/async_event.lua
blob: ef4bf4354401f9a617274343b879b1ad544008b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

local core = engine or minetest

core.async_jobs = {}

local function handle_job(jobid, serialized_retval)
	local retval = core.deserialize(serialized_retval)
	assert(type(core.async_jobs[jobid]) == "function")
	core.async_jobs[jobid](retval)
	core.async_jobs[jobid] = nil
end

if engine ~= nil then
	core.async_event_handler = handle_job
else
	minetest.register_globalstep(function(dtime)
		for i, job in ipairs(core.get_finished_jobs()) do
			handle_job(job.jobid, job.retval)
		end
	end)
end

function core.handle_async(func, parameter, callback)
	-- Serialize function
	local serialized_func = string.dump(func)

	assert(serialized_func ~= nil)

	-- Serialize parameters
	local serialized_param = core.serialize(parameter)

	if serialized_param == nil then
		return false
	end

	local jobid = core.do_async_callback(serialized_func, serialized_param)

	core.async_jobs[jobid] = callback

	return true
end