Traductions

Tout le monde doit pouvoir le lire

autant de langues que possible

Traduction

Il devait être possible de traduire facilement tout le jeu dans une autre langue. Après quelques essais, j’ai créé la classe I18n pour engine3. Pour l’instant, ce n’est rien de plus que ceci.

function I18n:new()
    self.locale = nil
    self.currentLocaleFile = nil
end

--- Convert string to i18n locale
---@param str? string
---@param replacements? table
function I18n:s(str, replacements)
    if str == nil then
        return
    end

    local strOut = tostring(str)

    -- Maybe there is a overwrite
    if self.locale[strOut] ~= nil then
        strOut = self.locale[strOut]
    end

    -- Maybe there are replacements
    if replacements then
        return string.gsub(strOut, "[%%%d]+", replacements)
    end

    return strOut
end

---@param file string
---@param data table
function I18n:createI18nData(file, data)
    self.locale = data
    self.currentLocaleFile = file
end

--- Load the locale in memory
---@param file string Path to the source file .mp only at the moment
function I18n:load(file)
    if type(file) ~= "string" then
        error("Cannot load i18n file, is not a string")
    end

    if string.find(file, ".mp") == nil then
        error("i18n file is is not supported: " .. file)
    end

    local msgPackData = Msgpack:load(file)
    if msgPackData == nil then
        error("File data is nil for file: " .. file)
        return
    end

    self:createI18nData(file, msgPackData)
end

Dans le jeu, on peut ensuite l’utiliser partout comme fonction globale, de cette façon

-- load the selected language once
i18n:load(config.localeDefault) -- nl.mp

-- use the default english strings into the selected language
local i18nHoverText = i18n:s("Hello")

language.yaml

en:
    "Hello" : null
nl:
    "Hello" : "Hallo"

Comme vous le voyez, la langue ’en’ figure aussi dans le language.yaml, mais avec la valeur null. Cela signifie que la phrase anglaise d’origine doit être utilisée. Il devient ainsi possible, à l’avenir, de traduire aussi l’anglais vers d’autres phrases.

en:
    "Hello z" : "Hallo y"
nl:
    "Hello z" : "Hallo y"
print(i18n:s("Hello z")) -- Hallo y

Pour l’instant, tout cela suffit et semble fonctionner bien et vite.