Logo Signal From The Stars

Translations

Everyone should be able to read it

Martin avatar
  • Martin
  • 2 min read
as many languages ​​as possible

Translation

It had to be possible to easily translate the entire game to another language. After some experiments I created the I18n class for engine3. At the moment it is nothing more than this.

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

In het spel kan het vervolgens al global function overal gebruikt worden op de volgende manier

-- 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"

As you can see the ’en’ language is also in the language.yaml but it has the value null. This means that the original English sentence must be used. This makes it possible to translate English to other sentences in the future.

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

For now this is all sufficient and seems to work well and quickly.


Loading external comment system...

βœ‰οΈ Stay informed!

Receive the latest news for free and motivate me to make this adventure a success!