Add modlib.minetest.playerdata

This commit is contained in:
Lars Mueller 2021-08-16 18:21:49 +02:00
parent e8b2d1c9d7
commit cb155021b1
2 changed files with 24 additions and 1 deletions

@ -23,7 +23,8 @@ for filename, comps in pairs{
"decode_base64",
"objects_inside_radius",
"objects_inside_area",
"nodename_matcher"
"nodename_matcher",
"playerdata",
},
liquid = {
"liquid_level_max",

@ -215,3 +215,25 @@ function nodename_matcher(node_or_groupname)
end
end
end
do
local default_create, default_free = function() return {} end, modlib.func.no_op
local metatable = {__index = function(self, player)
if type(player) == "userdata" then
return self[player:get_player_name()]
end
end}
function playerdata(create, free)
create = create or default_create
free = free or default_free
local data = {}
minetest.register_on_joinplayer(function(player)
data[player:get_player_name()] = create(player)
end)
minetest.register_on_leaveplayer(function(player)
data[player:get_player_name()] = free(player)
end)
setmetatable(data, metatable)
return data
end
end