summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author最萌小汐 <sumneko@hotmail.com>2018-12-29 13:42:16 +0800
committer最萌小汐 <sumneko@hotmail.com>2018-12-29 13:42:16 +0800
commitca3898fd7e8fa97d8b609b9a5578ef7d8af5e54d (patch)
tree7d29b8b29db59375e19076847d37b20e766c1af1
parent25f2563cda4381760d69010bdab2313551cb7e10 (diff)
downloadlua-language-server-ca3898fd7e8fa97d8b609b9a5578ef7d8af5e54d.zip
支持用id指定翻译参数
-rw-r--r--server/src/language.lua85
1 files changed, 56 insertions, 29 deletions
diff --git a/server/src/language.lua b/server/src/language.lua
index bf549132..ea5c01ae 100644
--- a/server/src/language.lua
+++ b/server/src/language.lua
@@ -44,6 +44,47 @@ local function loadFileByLanguage(name, language)
return tbl
end
+local function formatAsArray(str, ...)
+ local index = 0
+ local args = {...}
+ return str:gsub('%{(.-)%}', function (pat)
+ local id, fmt
+ local pos = pat:find(':', 1, true)
+ if pos then
+ id = pat:sub(1, pos-1)
+ fmt = pat:sub(pos+1)
+ else
+ id = pat
+ fmt = 's'
+ end
+ id = tonumber(id)
+ if not id then
+ index = index + 1
+ id = index
+ end
+ return ('%'..fmt):format(args[id])
+ end)
+end
+
+local function formatAsTable(str, ...)
+ local args = ...
+ return str:gsub('%{(.-)%}', function (pat)
+ local id, fmt
+ local pos = pat:find(':', 1, true)
+ if pos then
+ id = pat:sub(1, pos-1)
+ fmt = pat:sub(pos+1)
+ else
+ id = pat
+ fmt = 's'
+ end
+ if not id then
+ return
+ end
+ return ('%'..fmt):format(args[id])
+ end)
+end
+
local function loadLang(name, language)
local tbl = loadFileByLanguage(name, 'en-US')
if language ~= 'en-US' then
@@ -59,35 +100,21 @@ local function loadLang(name, language)
end,
__call = function (self, key, ...)
local str = self[key]
- local index = 0
- local args = {...}
- return str:gsub('%{(.-)%}', function (pat)
- local id, fmt
- local pos = pat:find(':', 1, true)
- if pos then
- id = pat:sub(1, pos-1)
- fmt = pat:sub(pos+1)
- else
- id = pat
- fmt = 's'
- end
- id = tonumber(id)
- if not id then
- index = index + 1
- id = index
- end
- local v = args[id]
- local suc, res = pcall(string.format, '%'..fmt, v)
- if suc then
- return res
- else
- -- 这里不能使用翻译,以免死循环
- log.warn(('[%s][%s-%s]{%s} formated error.'):format(
- language, name, key, pat
- ))
- return nil
- end
- end)
+ local suc, res
+ if type(...) == 'table' then
+ suc, res = pcall(formatAsTable, str, ...)
+ else
+ suc, res = pcall(formatAsArray, str, ...)
+ end
+ if suc then
+ return res
+ else
+ -- 这里不能使用翻译,以免死循环
+ log.warn(('[%s][%s-%s] formated error: %s'):format(
+ language, name, key, str
+ ))
+ return str
+ end
end,
})
end