diff --git a/system/chat_commands.lua b/system/chat_commands.lua index eff0253..8e57bbd 100644 --- a/system/chat_commands.lua +++ b/system/chat_commands.lua @@ -13,6 +13,43 @@ local colorize = function (color, string) end +-- Validate a new value +-- +-- 1. Check if setting is valid at all +-- 2. If `show` has to be set, validate for 'true' or 'false' string +-- 3. Validate against a simple regex +-- 4. If all of the above was not `nil`, return `true` +-- +-- @param setting The setting the value is for +-- @param new_value The new value that has to be validated +-- @return bool If the new value for the setting is valid or not +local validate = function (setting, new_value) + local valid_values = { + runtime = '^[^%c]+$', + offset = '^%-?[0-9]+,%-?[0-9]+$', + ingame_time = '^[^%c]+$', + current_time = '^[^%c]+$', + font_color = '^[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$', + start = '^[^%c]+$', + show = '^$', -- unmatchable, see below + locale = '^$', -- currently unsupported and not settable by user + position = '^%-?[0-9]+,%-?[0-9]+$', + format = '^[^%c]+$', + alignment = '^%-?[0-9]+,%-?[0-9]+$' + } + + if valid_values[setting] == nil then return false end + + -- Check if `new_value` for setting `show` is either 'true' or 'false' and + -- return true in both cases (because either 'true' or 'false' are valid). + if setting == 'show' and new_value == 'true' then return true end + if setting == 'show' and new_value == 'false' then return true end + + if new_value:match(valid_values[setting]) == nil then return false end + return true +end + + -- Show help to the player -- -- @param player The player to show the help to @@ -67,6 +104,36 @@ local show_configuration = function (player) end +local set = function (player, payload) + local name = player:get_player_name() + local setting = payload:match('[%a_]+') + local new_value = payload:gsub('^[%a_]+ ', '') + local old_value = player:get_attribute('mtimer:'..setting) + local status = '' + + if old_value == nil then + minetest.chat_send_player(name, colorize('ef2929', 'Unknown setting!')) + show_configuration(player) + return + end + + if validate(setting, new_value) == false then + minetest.chat_send_player(name, colorize('ef2929', 'Invalid value!')) + show_configuration(player) + return + end + + status = status..colorize('729fcf', '[MTimer]')..' ' + status = status..'Setting '..colorize('73d216', setting)..' to ' + status = status..colorize('75507b', new_value) + + print('[MTimer] '..name..' sets `'..setting..'` to `'..new_value..'`') + minetest.chat_send_player(name, status) + player:set_attribute('mtimer:'..setting, new_value) + mtimer_update(player) +end + + -- Register the chat command that will be used to interact with MTimer. -- -- The chat command has three actions: