How about something like this?
translationSystem.lua
Code: Select all
local languages = {}
local currentLanguage
do
local files = love.filesystem.getDirectoryItems('lang/')
for _, v in ipairs(files) do
v = string.sub(v, 1, -5)
languages[v] = require('lang/' .. v)
end
end
local function setLanguage(l)
if l then
assert(languages[l], string.format('No such language: "%s"', l))
end
currentLanguage = l
end
local function getLanguages()
local langs = {}
for k, _ in pairs(languages) do
table.insert(langs, k)
end
return langs
end
local function tr(_, str)
return currentLanguage and languages[currentLanguage][str] or str
end
return setmetatable({
setLanguage = setLanguage,
getLanguages = getLanguages
}, {__call = tr})
Here is an example with example language files:
main.lua
Code: Select all
local tr
function love.load()
tr = require('translationSystem')
end
function love.draw()
local y = 0
local function printMsg(lang)
tr.setLanguage(lang)
love.graphics.print(tr('I love apples'), 0, y)
love.graphics.print(tr('I hope you love them too!'), 0, y + 16)
y = y + 48
end
-- Source language
printMsg()
-- All supported languages
for _, lang in ipairs(tr.getLanguages()) do
printMsg(lang)
end
end
langs/german.lua
Code: Select all
return {
['I love apples'] = 'Ich liebe Äpfel',
['I hope you love them too!'] = 'Ich hoffe dass Sie sie auch lieben!'
}
langs/hungarian.lua:
Code: Select all
return {
['I love apples'] = 'Szeretem az almákat',
['I hope you love them too!'] = 'Remélem te is szereted őket!'
}
One problem with this solution though:
Some words/phrases can potentially have different translations in different contexts.
This translation system does not account for that.
If you want, I might cook something up, but I wanted to keep it simple.