From 55d9ed1709933a7994e5107f2c1fb300334a92ec Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:46:02 +1000 Subject: [PATCH] refactor(settings): safeGetKvp If the kvp has an unexpected type for whatever reason, clear it. --- resource/settings.lua | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/resource/settings.lua b/resource/settings.lua index ccc707150..cfcbac3c8 100644 --- a/resource/settings.lua +++ b/resource/settings.lua @@ -4,15 +4,30 @@ if GetResourceKvpInt('reset_locale') ~= 1 then SetResourceKvpInt('reset_locale', 1) end +---@generic T +---@param fn fun(key): unknown +---@param key string +---@param default? T +---@return T +local function safeGetKvp(fn, key, default) + local ok, result = pcall(fn, key) + + if not ok then + return DeleteResourceKvp(key) + end + + return result or default +end + local settings = { default_locale = GetConvar('ox:locale', 'en'), - notification_position = GetResourceKvpString('notification_position') or 'top-right', - notification_audio = GetResourceKvpInt('notification_audio') == 1 + notification_position = safeGetKvp(GetResourceKvpString, 'notification_position', 'top-right'), + notification_audio = safeGetKvp(GetResourceKvpInt, 'notification_audio') == 1 } local userLocales = GetConvarInt('ox:userLocales', 1) == 1 -settings.locale = userLocales and GetResourceKvpString('locale') or settings.default_locale +settings.locale = userLocales and safeGetKvp(GetResourceKvpString, 'locale') or settings.default_locale local function set(key, value) if settings[key] == value then return false end