Boris Nagaev · Home page | About | Contact | Github | Code | FBB files

Lua MO files parser translates Lapis site

The parser for MO files was packaged for LuaRocks and uploaded to LuaRocks site as rock “mo”. It is available for installation under terms of MIT license.

$ luarocks install mo

MO file is binary format of GNU gettext used to store translations. It is created from PO file using tool msgfmt. It can be used to translate an application or a site from English to other language.

J.Jørgen von Bargen sent the code of parser to lua-l mailing list on Apr, 01, 2010. I have changed behavior of the function: now it returns translating function in case of success and function(x) return x end in case of errors. The code was covered with unit tests with coverage 100%. Unit tests are written using unit testing framework Busted.

Where mo.lua is used

I use this package in code of my site kodomoquiz, based on Lapis. “mo” is used in many files of kodomoquiz, e.g. in file app.lua (as variable _).

Let us translate some Lua project into Russian.

$ xgettext -p ru -s -j --language=Lua *.lua --from-code utf-8

This command creates (or adds to) file ru/messages.po. It finds texts like _("text") in source files and adds them to .po file.

There are a lot of programs to translate .po file. One of them is poedit.

To compile .po to .mo, run the following command:

$ msgfmt ru/messages.po -o ru/

Module mo.lua is used to parse .mo file from Lua:

-- load mo.lua
mo = require 'mo'

-- load .mo file with translations
-- returns translating function on success
-- returns nil, 'error message' on failure
_ = mo('')

-- translate from English into Russian
print(_("hello")) -- prints "привет"
-- the function returns its argument if it can't translate it
print(_("unknown phrase")) -- prints "unknown phrase"

See also