Skip to content

Instantly share code, notes, and snippets.

@NotMyWing
Created October 16, 2018 01:58
Show Gist options
  • Save NotMyWing/e3b3097e7d1a71aeb455d49ee0a5eb4f to your computer and use it in GitHub Desktop.
Save NotMyWing/e3b3097e7d1a71aeb455d49ee0a5eb4f to your computer and use it in GitHub Desktop.
lol
class EndlessKeyValuePair
new: (__value) =>
rawset @, "__value", __value
dotcut = (str) ->
pos = (string.find str, "%.") or 0
key = str\sub 1, pos - 1
remainder = str\sub pos + 1, -1
return key, (pos ~= 0) and remainder or nil
meta = getmetatable @
meta.__call = (...) =>
value = rawget @, "__value"
if (type value) == "function"
value ...
elseif (type value) == "string"
string.format value, ...
else
nil
meta.__tostring = =>
value = rawget @, "__value"
if (type value) == "function"
value!
else
tostring value
meta.__index = (key) =>
if (type key) == "number"
key = tostring key
if (type key) ~= "string"
error "The key must be a string"
if key\find "%."
key, rem = dotcut key
keyvaluepair = rawget @, key
if not keyvaluepair
keyvaluepair = EndlessKeyValuePair!
rawset @, key, keyvaluepair
keyvaluepair[rem]
else
keyvaluepair = rawget @, key
if not keyvaluepair
keyvaluepair = EndlessKeyValuePair!
rawset @, key, keyvaluepair
keyvaluepair
meta.__newindex = (key, value) =>
if (type key) == "number"
key = tostring key
if (type key) ~= "string"
error "The key must be a string"
local remainder
if key\find "%."
key, rem = dotcut key
keyvaluepair = rawget @, key
if not keyvaluepair
keyvaluepair = EndlessKeyValuePair!
rawset @, key, keyvaluepair
keyvaluepair[rem] = value
else
keyvaluepair = rawget @, key
if not keyvaluepair
keyvaluepair = EndlessKeyValuePair value
rawset @, key, keyvaluepair
else
rawset keyvaluepair, "__value", value
class Nee18n
getCurrent: ->
if SERVER
"en"
else
GetConVarString "gmod_language"
keys:
EndlessKeyValuePair!
translateTo: (language, key, ...) ->
-- TO:DO
translateToCurrent: (...) ->
@translate @getCurrent, ...
export Nee18n = Nee18n!
-- TODO: this garbage belongs to tests/ci
Nee18n.keys.a.a = "foo"
Nee18n.keys.a.b = "bar"
Nee18n.keys.a.d = "buz"
Nee18n.keys["a.b.c.d.e.f"] = "abcdef %s"
print "a: " .. tostring Nee18n.keys.a
print "a.a: " .. tostring Nee18n.keys.a.a
print "a.b: " .. tostring Nee18n.keys.a.b
print "a.d: " .. tostring Nee18n.keys.a.d
print "a.b.c.d.e.f: " .. tostring Nee18n.keys.a.b.c.d.e.f
print "a.b.c.d.e.f / call: " .. tostring Nee18n.keys.a.b.c.d.e.f "call"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment