-
Notifications
You must be signed in to change notification settings - Fork 6
/
languages.lua
111 lines (99 loc) · 2.71 KB
/
languages.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
---@type string | false
local defaultLang=false
local maxLangLoaded=3
local langLoaded={}
local langPaths={}
local langLib={
[false]={},
}
setmetatable(langLib,{
__index=function(self,k)
local lang=FILE.load(langPaths[k],'-luaon')
setmetatable(lang,{__index=langLib[k~=defaultLang and defaultLang]})
self[k]=lang
table.insert(langLoaded,k)
if #langLoaded>maxLangLoaded then
for i=1,#langLoaded do
if langLoaded[i]~=defaultLang then
langLib[table.remove(langLoaded,i)]=nil
break
end
end
end
return self[k]
end,
})
setmetatable(langLib[false],{
__index=function(self,k)
self[k]='['..k..']'
return self[k]
end,
})
local LANG={}
---Set the default language
---@param name string
function LANG.setDefault(name)
assert(type(name)=='string',"LANG.setDefault(name): Need string")
defaultLang=name
for k,v in next,langLib do
if k~=false then
setmetatable(v,{__index=langLib[k~=defaultLang and defaultLang]})
end
end
end
---Set the max loaded language count
---@param n number
function LANG.setMaxLoaded(n)
assert(type(n)=='number' and n>=1 and n%1==0,"LANG.setMaxLoaded(n): Need int >1")
maxLangLoaded=n
end
---Add language file info list
---@param data table<string, string> name-path
function LANG.add(data)
for k,v in next,data do
assert(type(k)=='string' and type(v)=='string',"LANG.add(data): Need {zh='path1',en='path2',...}")
langPaths[k]=v
end
end
---Get a language table, which can be used to get texts like `languageTable.opt --> 'Option'`
---@param name string
---@return table
function LANG.get(name)
return langLib[name]
end
local textSrc=langLib[false]
---Set the text function source
---@param newSrc table
function LANG.setTextFuncSrc(newSrc)
assert(type(newSrc)=='table',"LANG.setTextFuncSrc(newSrc): Need table")
textSrc=newSrc
end
---Shortcut of LANG.get+LANG.setTextFuncSrc, return the language table like LANG.get
---@param name string
---@return table
function LANG.set(name)
LANG.setTextFuncSrc(LANG.get(name))
return textSrc
end
local textFuncs=setmetatable({},{
__index=function(self,k)
self[k]=function() return textSrc[k] end
return self[k]
end,
})
---Get a text-getting function, useful on UI texts i18n
---
---You can use LANG('key') instead of LANG.getTextFunc('key')
---@param key string
---@return fun(): string
function LANG.getTextFunc(key)
return textFuncs[key]
end
setmetatable(LANG,{
-- Works same as LANG.getTextFunc
__call=function(_,key)
return textFuncs[key]
end,
__metatable=true,
})
return LANG