I built a Lua web application and it's become clear that I need to begin internationalizing ("i18n") it for my overseas customers.
In Lua, what's the best way to internationalization my application?
I realize this is a significant undertaking, especially since some of my display is hard coded in HTML templates and some data fields are in my currently US-english oriented database.
Any guidance would be appreciated.
Edit: added metatable stuff
Would someone mind making the example code above a little more clear
Certainly.
In one file you define a i18n
variable with the following methods:
local i18n = { locales = {} }
local currentLocale = 'en' -- the default language
function i18n.setLocale(newLocale)
currentLocale = newLocale
assert(i18n.locales[currentLocale], ("The locale %q was unknown"):format(newLocale))
end
local function translate(id)
local result = i18n.locales[currentLocale][id]
assert(result, ("The id %q was not found in the current locale (%q)"):format(id, currentLocale)
return result
end
i18n.translate = translate
setmetatable(i18n, {__call = function(_,...) return translate(id) end})
return i18n
In the same file, or in other(s), you include the locales you need inside i18n.locales
.
local i18n = require 'i18n' -- remove this line if on the same file as before
i18n.locales.en = {
helloWorld = "Hello world",
loginWarning = "You need to be logged in to do that"
}
i18n.locales.es = {
helloWorld = "Hola mundo",
loginWarning = "Debes haber iniciado una sesión para hacer eso"
}
...
Usage:
local i18n = require 'i18n'
require 'locales' -- if using a separate file for the locales, require it too
print( i18n.translate('helloWorld') ) -- Hello world
i18n.setLocale('es')
-- using i18n() instead of i18n.translate()
print( i18n('helloWorld') ) -- Hola mundo
In Lua it's pretty easy to use translation tables. First write you code so that every string that needs to be translated is used via a function call, as in say i18n"Hello World"
. Then write translation tables for the languages you want to support. For instance, English={["Hello World"]="Hello World"}
(or add an index metamethod that simply returns the key, to avoid repeating strings) and French={["Hello World"]="Salut le monde"}
. Finally write function i18n(s) return Language[s] end
and so set Language=French
when you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With