From c57b1a9215f8a24cec3b432b6d691a070bbba0a4 Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Thu, 23 Feb 2023 18:54:49 +1100 Subject: [PATCH] fix(imports/locale): prevent error from invalid locales People with poorly formatted json files would not get a locales table, leading to an error when trying to iterate. Contains some other inconsequential changes, and warnings. --- imports/locale/shared.lua | 40 +++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/imports/locale/shared.lua b/imports/locale/shared.lua index a61e25e..014e816 100644 --- a/imports/locale/shared.lua +++ b/imports/locale/shared.lua @@ -1,29 +1,45 @@ +---@type { [string]: string } local dict = {} ---@param str string ---@param ... string | number ---@return string function locale(str, ...) - local lstr = dict[str] + local lstr = dict[str] - if lstr then - if ... then - return lstr and lstr:format(...) - end + if lstr then + if ... then + return lstr and lstr:format(...) + end - return lstr - end + return lstr + end - return str + return str end ----@return { [string]: string } function lib.getLocales() return dict end -function lib.loadLocale() - local locales = json.decode(LoadResourceFile(cache.resource, ('locales/%s.json'):format(GetConvar('ox:locale', 'en'))) or LoadResourceFile(cache.resource, 'locales/en.json') or '[]') +function lib.locale() + local lang = GetConvar('ox:locale', 'en') + local locales = json.decode(LoadResourceFile(cache.resource, ('locales/%s.json'):format(lang))) + + if not locales then + local warning = "could not load 'locales/%s.json'" + warn(warning:format(lang)) + + if lang ~= 'en' then + locales = json.decode(LoadResourceFile(cache.resource, 'locales/en.json')) + + if not locales then + warn(warning:format('en')) + end + end + + if not locales then return end + end for k, v in pairs(locales) do if type(v) == 'string' then @@ -41,4 +57,4 @@ function lib.loadLocale() end end -return lib.loadLocale +return lib.locale