feat: add Lua runtime storage API

This commit is contained in:
gem
2026-06-10 11:31:17 +08:00
parent 8ddc3be3a7
commit 6608d0a975
5 changed files with 162 additions and 1 deletions

View File

@@ -8,6 +8,7 @@ import '../models/game_diff.dart';
import '../models/runtime_event.dart';
import '../network/runtime_network_manager.dart';
import '../packages/game_package.dart';
import '../storage/runtime_storage_manager.dart';
import 'runtime_script_services.dart';
import 'script_engine.dart';
@@ -166,6 +167,18 @@ class LuaDardoScriptEngine implements ScriptEngine {
_lua.pushDartFunction(_hostRespond);
_lua.setField(-2, 'host_respond');
_lua.pushDartFunction(_storageGet);
_lua.setField(-2, 'storage_get');
_lua.pushDartFunction(_storageSet);
_lua.setField(-2, 'storage_set');
_lua.pushDartFunction(_storageRemove);
_lua.setField(-2, 'storage_remove');
_lua.pushDartFunction(_storageClear);
_lua.setField(-2, 'storage_clear');
_lua.setGlobal('runtime');
}
@@ -272,6 +285,43 @@ class LuaDardoScriptEngine implements ScriptEngine {
return 1;
}
int _storageGet(LuaState lua) {
final storage = _requireStorage();
final key = lua.toStr(1);
if (key == null || key.isEmpty) {
throw const FormatException('runtime.storage_get(key, defaultValue) requires key');
}
final defaultValue = _readValue(2);
_pushValue(storage.getValue(key, defaultValue));
return 1;
}
int _storageSet(LuaState lua) {
final storage = _requireStorage();
final key = lua.toStr(1);
if (key == null || key.isEmpty) {
throw const FormatException('runtime.storage_set(key, value) requires key');
}
final value = _readValue(2);
lua.pushBoolean(storage.setValue(key, value));
return 1;
}
int _storageRemove(LuaState lua) {
final storage = _requireStorage();
final key = lua.toStr(1);
if (key == null || key.isEmpty) {
throw const FormatException('runtime.storage_remove(key) requires key');
}
lua.pushBoolean(storage.remove(key));
return 1;
}
int _storageClear(LuaState lua) {
lua.pushBoolean(_requireStorage().clear());
return 1;
}
RuntimeHostBridgeManager _requireHostBridge() {
final hostBridge = _services.hostBridge;
if (hostBridge == null) {
@@ -293,6 +343,14 @@ class LuaDardoScriptEngine implements ScriptEngine {
return network;
}
RuntimeStorageManager _requireStorage() {
final storage = _services.storage;
if (storage == null) {
throw StateError('Runtime storage service is not installed');
}
return storage;
}
String _nextNetworkRequestId(String prefix) {
_networkRequestCounter += 1;
return '$prefix:$_networkRequestCounter';