lua-users home
lua-l archive

Re: String access & metamethods

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


On Dec 12, 2007 9:36 PM, Brett Kugler <bkugler@gmail.com> wrote:
> I realize I could simplify my life with a little extra notation, but the
> hope was to really not change my existing code at all and have the string
> literals be reinterpreted based on a new metamethod instead. Am I grasping
> at straws?
This solution is akin to Stefan's: we create a special table 'msg'
which has an __index metamethod which returns the appropriate string
version of the message word.
-- messages.lua
local translations = {
 DidNotWork = {
 "Operation did not succeed",
 "Operasie het nie geslaag nie"
 },
 NoAnswer = {
 "No answer found",
 "Antwoord nie gefind nie",
 }
}
msg = {
 English = 1,
 Afrikaans = 2,
}
function get_translation(t,word)
 local res = translations[word][msg.language]
 if not res then return "cannot find translation" end
 return res
end
setmetatable(msg,{__index=get_translation})
And it would be used like this:
require 'messages"
msg.language = msg.Afrikaans
print(msg.DidNotWork)
print(msg.NoAnswer)
steve d.

AltStyle によって変換されたページ (->オリジナル) /