Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - How to do Internationalization? [closed]

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.

like image 288
nickb Avatar asked Jan 16 '12 21:01

nickb


2 Answers

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
like image 91
kikito Avatar answered Nov 18 '22 08:11

kikito


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.

like image 44
lhf Avatar answered Nov 18 '22 10:11

lhf