From b3c8889b95e6430d363f80ebcdd011de115c9a3d Mon Sep 17 00:00:00 2001 From: whosit Date: Wed, 23 Jun 2021 02:44:01 +0300 Subject: [PATCH] reduce number of gsub calls for text variable substitutions Use lua feature that allows to specify table with substitutions to string.gsub() --- functions.lua | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/functions.lua b/functions.lua index 95d0c5d..ba55a2d 100644 --- a/functions.lua +++ b/functions.lua @@ -3112,11 +3112,12 @@ end -- replace some variables in the text the NPC speaks and which the player can use to reply -- pname: the name of the player that is talking to the NPC yl_speak_up.replace_vars_in_text = function(text, dialog, pname) - -- Note: the $ char is a special one. It needs to be escaped with %$ in lua. - text = string.gsub(text, "%$MY_NAME%$", dialog.n_npc) - text = string.gsub(text, "%$NPC_NAME%$", dialog.n_npc) - text = string.gsub(text, "%$OWNER_NAME%$", dialog.npc_owner) - text = string.gsub(text, "%$PLAYER_NAME%$", pname) + local subs = { + MY_NAME = dialog.n_npc, + NPC_NAME = dialog.n_npc, + OWNER_NAME = dialog.npc_owner, + PLAYER_NAME = pname, + } local day_time_name = "day" local day_time = minetest.get_timeofday() @@ -3127,8 +3128,15 @@ yl_speak_up.replace_vars_in_text = function(text, dialog, pname) else day_time_name = "evening" end - text = string.gsub(text, "%$GOOD_DAY%$", "Good "..day_time_name) - text = string.gsub(text, "%$good_DAY%$", "good "..day_time_name) + subs.GOOD_DAY = "Good "..day_time_name + subs.good_DAY = "good "..day_time_name + + -- Note: the $ char is a special one. It needs to be escaped with %$ in lua. + -- Note: when substitution argument is a table, we look up + -- substitutions in it using substring captured by "()" in + -- pattern. "[%a_]+" means one or more letter or underscore. + -- If lookup returns nil, then no substitution is made. + text = string.gsub(text, "%$([%a_]+)%$", subs) return text end -- 2.47.2