mirror of
https://github.com/minetest/minetest.git
synced 2024-12-15 02:39:21 +01:00
Use a safer implementation of gsub in core.chat_format_message (#9133)
This search-and-replace implementation does not use Lua pattern-matching
This commit is contained in:
parent
1c61fe5ed9
commit
fa858530cc
@ -1,27 +1,41 @@
|
|||||||
-- Minetest: builtin/game/chat.lua
|
-- Minetest: builtin/game/chat.lua
|
||||||
|
|
||||||
|
-- Helper function that implements search and replace without pattern matching
|
||||||
|
-- Returns the string and a boolean indicating whether or not the string was modified
|
||||||
|
local function safe_gsub(s, replace, with)
|
||||||
|
local i1, i2 = s:find(replace, 1, true)
|
||||||
|
if not i1 then
|
||||||
|
return s, false
|
||||||
|
end
|
||||||
|
|
||||||
|
return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
|
||||||
|
end
|
||||||
|
|
||||||
--
|
--
|
||||||
-- Chat message formatter
|
-- Chat message formatter
|
||||||
--
|
--
|
||||||
|
|
||||||
-- Implemented in Lua to allow redefinition
|
-- Implemented in Lua to allow redefinition
|
||||||
function core.format_chat_message(name, message)
|
function core.format_chat_message(name, message)
|
||||||
local str = core.settings:get("chat_message_format")
|
|
||||||
local error_str = "Invalid chat message format - missing %s"
|
local error_str = "Invalid chat message format - missing %s"
|
||||||
local i
|
local str = core.settings:get("chat_message_format")
|
||||||
|
local replaced
|
||||||
|
|
||||||
str, i = str:gsub("@name", name, 1)
|
-- Name
|
||||||
if i == 0 then
|
str, replaced = safe_gsub(str, "@name", name)
|
||||||
|
if not replaced then
|
||||||
error(error_str:format("@name"), 2)
|
error(error_str:format("@name"), 2)
|
||||||
end
|
end
|
||||||
|
|
||||||
str, i = str:gsub("@message", message, 1)
|
-- Timestamp
|
||||||
if i == 0 then
|
str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
|
||||||
|
|
||||||
|
-- Insert the message into the string only after finishing all other processing
|
||||||
|
str, replaced = safe_gsub(str, "@message", message)
|
||||||
|
if not replaced then
|
||||||
error(error_str:format("@message"), 2)
|
error(error_str:format("@message"), 2)
|
||||||
end
|
end
|
||||||
|
|
||||||
str = str:gsub("@timestamp", os.date("%H:%M:%S", os.time()), 1)
|
|
||||||
|
|
||||||
return str
|
return str
|
||||||
end
|
end
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user