-- LUALOCALS < ---------------------------------------------------------
local error, ipairs, klots, minetest, type
    = error, ipairs, klots, minetest, type
-- LUALOCALS > ---------------------------------------------------------

function klots.register_playerstep(def)
	if type(def) == "function" then def = {on_step = def} end
	if not def.on_step then return error("def.on_step required") end

	local player_data = {}

	local function getdata(player_or_name)
		local pname = type(player_or_name) == "string"
		and player_or_name or player_or_name:get_player_name()
		local data = player_data[pname]
		if not data then
			data = {}
			if def.on_init then
				local player = type(player_or_name) == "string"
				and minetest.get_player_by_name(player_or_name)
				or player_or_name
				def.on_init(player, data)
			end
			player_data[pname] = data
		end
		return data
	end

	minetest.register_globalstep(function(dtime)
			for _, player in ipairs(minetest.get_connected_players()) do
				local pname = player:get_player_name()
				def.on_step(player, getdata(pname), dtime)
			end
		end)

	if def.on_leave then
		minetest.register_on_leaveplayer(function(player)
				local pname = player:get_player_name()
				def.on_leave(player, getdata(pname))
				player_data[pname] = nil
			end)
	end

	return getdata
end
