lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Dec 12, 2007 2:02 PM, Brett Kugler <bkugler@gmail.com> wrote:
> t={}
> t["english1"]={"english1","spanish1","french1"}
> t["english2"]={"english2","spanish2","french2"}
> t["english3"]={"english3","spanish3","french3"}

You don't need the English version twice. This will do just as well:

t["english1"]={"spanish1","french1"}
t["english2"]={"spanish2","french2"}
t["english3"]={"spanish3","french3"}

Since your __tostring function defaults to the English string anyway.

> getmetatable("").__tostring=function(in_string)
>     if t[in_string] ~= nil and t[in_string][language] ~= nil then
>
>         return t[in_string][language]
>     else
>         return in_string
>     end
> end

There's a handy Lua idiom for code like that:

getmetatable("").__tostring = function(s)
    return t[s] and t[s][language] or s
end

> print("english1")
> a_value="english2"
> print(a_value)

You should be aware that this works because print calls 'tostring' on
it's arguments. You will not get automatic translation in other
places:

   io.write("english1")

   error("english1")

   print("english1" .. "english1")

You would need to explicitly call tostring():

   io.write(tostring("english1"))

   error(tostring("english1"))

   print(tostring("english1") .. tostring("english1"))

At that point, you're better off just calling a localization function,
because it's *clearer*.  It's easier to maintain straightforward code
than 'clever' code.

In this case you have a more bigger maintenance issue: duplicating data.

   localized = {
     ["Record not found. Contact system administator"]={"spanish
version","french version"},
     ...
   }

   ...

   print("Record not found. Contact system administator")


You have the same string literal in two different places. If you're
looking over the code later and notice that you misspelled
"administrator", you need to remember to fix it in both places or your
localization breaks. Worse, there's nothing at the point of use (the
print statement) to indicate that localization is happening. The
code's not self documenting, and easy broken.

Better to just use a identifier for the error message (like
RECORD_NOT_FOUND, which is defined according to the current language)
rather than a literal string which automagically changes value.

Cheers,
Eric