|
1 | 1 | -- Minetest: builtin/game/chat.lua
|
2 | 2 |
|
| 3 | +-- Helper function that implements search and replace without pattern matching |
| 4 | +-- Returns the string and a boolean indicating whether or not the string was modified |
| 5 | +local function safe_gsub(s, replace, with) |
| 6 | + local i1, i2 = s:find(replace, 1, true) |
| 7 | + if not i1 then |
| 8 | + return s, false |
| 9 | + end |
| 10 | + |
| 11 | + return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true |
| 12 | +end |
| 13 | + |
3 | 14 | --
|
4 | 15 | -- Chat message formatter
|
5 | 16 | --
|
6 | 17 |
|
7 | 18 | -- Implemented in Lua to allow redefinition
|
8 | 19 | function core.format_chat_message(name, message)
|
9 |
| - local str = core.settings:get("chat_message_format") |
10 | 20 | local error_str = "Invalid chat message format - missing %s"
|
11 |
| - local i |
| 21 | + local str = core.settings:get("chat_message_format") |
| 22 | + local replaced |
12 | 23 |
|
13 |
| - str, i = str:gsub("@name", name, 1) |
14 |
| - if i == 0 then |
| 24 | + -- Name |
| 25 | + str, replaced = safe_gsub(str, "@name", name) |
| 26 | + if not replaced then |
15 | 27 | error(error_str:format("@name"), 2)
|
16 | 28 | end
|
17 | 29 |
|
18 |
| - str, i = str:gsub("@message", message, 1) |
19 |
| - if i == 0 then |
| 30 | + -- Timestamp |
| 31 | + str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time())) |
| 32 | + |
| 33 | + -- Insert the message into the string only after finishing all other processing |
| 34 | + str, replaced = safe_gsub(str, "@message", message) |
| 35 | + if not replaced then |
20 | 36 | error(error_str:format("@message"), 2)
|
21 | 37 | end
|
22 | 38 |
|
23 |
| - str = str:gsub("@timestamp", os.date("%H:%M:%S", os.time()), 1) |
24 |
| - |
25 | 39 | return str
|
26 | 40 | end
|
27 | 41 |
|
|
0 commit comments