From cb155021b1c6160906a8ea32ab1c1419ca2aaa0b Mon Sep 17 00:00:00 2001 From: Lars Mueller Date: Mon, 16 Aug 2021 18:21:49 +0200 Subject: [PATCH] Add modlib.minetest.playerdata --- minetest.lua | 3 ++- minetest/misc.lua | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/minetest.lua b/minetest.lua index d388697..3837afd 100644 --- a/minetest.lua +++ b/minetest.lua @@ -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", diff --git a/minetest/misc.lua b/minetest/misc.lua index f752da2..1cc0ec7 100644 --- a/minetest/misc.lua +++ b/minetest/misc.lua @@ -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