feat: add runtime i18n API with manifest translations

This commit is contained in:
gem
2026-06-12 10:19:14 +08:00
parent 79ee35db2f
commit 4ea3663853
8 changed files with 141 additions and 0 deletions

View File

@@ -71,6 +71,69 @@ class LuaDardoScriptEngine implements ScriptEngine {
}
}
@override
void setTranslations({
required String locale,
required Map<String, Map<String, String>> translations,
}) {
_lua.getGlobal('runtime');
if (_lua.isNil(-1)) {
_lua.pop(1);
return;
}
_lua.newTable();
_lua.pushString(locale);
_lua.setField(-2, 'locale');
_lua.pushDartFunction((LuaState lua) {
lua.pushString(locale);
return 1;
});
_lua.setField(-2, 'get_locale');
_lua.pushDartFunction((LuaState lua) {
final key = lua.toStr(1);
if (key == null || key.isEmpty) {
if (lua.getTop() >= 2 && !lua.isNil(2)) {
lua.pushValue(2);
} else {
lua.pushString(key ?? '');
}
return 1;
}
final localeDict = translations[locale];
final value = localeDict?[key];
if (value != null) {
lua.pushString(value);
return 1;
}
for (final entry in translations.entries) {
if (entry.key != locale) {
final fallbackValue = entry.value[key];
if (fallbackValue != null) {
lua.pushString(fallbackValue);
return 1;
}
}
}
if (lua.getTop() >= 2 && !lua.isNil(2)) {
lua.pushValue(2);
} else {
lua.pushString(key);
}
return 1;
});
_lua.setField(-2, 't');
_lua.setField(-2, 'i18n');
_lua.pop(1);
}
@override
bool smokeTest(Map<String, Object?> context) {
_lua.getGlobal('smoke_test');

View File

@@ -22,4 +22,10 @@ abstract interface class ScriptEngine {
GameDiff init(Map<String, Object?> context);
GameDiff dispatchEvent(RuntimeEvent event);
/// 设置翻译字典和当前语言Lua 侧可通过 runtime.i18n.t(key, fallback) 查询。
void setTranslations({
required String locale,
required Map<String, Map<String, String>> translations,
});
}