Implement storage feature - save state variables locally.

This commit is contained in:
Condorra 2024-11-06 21:48:04 +11:00
parent a1b53923ac
commit 6122ac7926
2 changed files with 33 additions and 1 deletions

View File

@ -1,4 +1,4 @@
use self::{frameroutes::*, frames::*, muds::*};
use self::{frameroutes::*, frames::*, muds::*, storage::*};
use anyhow::Error;
use piccolo::{
async_callback::{AsyncSequence, Locals},
@ -29,6 +29,7 @@ pub struct LuaState {
mod frameroutes;
pub mod frames;
pub mod muds;
pub mod storage;
impl LuaState {
pub fn setup() -> Result<LuaState, String> {
@ -196,6 +197,7 @@ pub fn install_lua_globals(
register_command!(mud_log, "log");
register_command!(panel_merge);
register_command!(sendmud_raw);
register_stateless_command!(storage);
register_command!(tick);
register_stateless_command!(mud_trigger, "untrigger");
register_stateless_command!(mud_untrigger, "unact");

30
src/lua_engine/storage.rs Normal file
View File

@ -0,0 +1,30 @@
use anyhow::anyhow;
use piccolo::{Callback, CallbackReturn, Context, IntoValue, Value};
use web_sys::window;
pub fn storage<'gc>(ctx: Context<'gc>) -> Callback<'gc> {
Callback::from_fn(&ctx, |ctx, _ex, mut stack| {
let local_storage = window()
.ok_or_else(|| anyhow!("Can't get window"))?
.local_storage()
.map_err(|e| anyhow!("Local storage error: {}", e.as_string().unwrap_or_default()))?
.ok_or_else(|| anyhow!("Can't get localstorage"))?;
let varname: String = stack.from_front(ctx)?;
let ls_varname: String = format!("userstorage_{}", varname);
if stack.is_empty() {
let result = local_storage.get(&ls_varname).map_err(|e| {
anyhow!("Local storage error: {}", e.as_string().unwrap_or_default())
})?;
match result {
None => stack.push_back(Value::Nil),
Some(s) => stack.push_back(s.into_value(ctx)),
}
} else {
let value: String = stack.from_front(ctx)?;
local_storage.set(&ls_varname, &value).map_err(|e| {
anyhow!("Local storage error: {}", e.as_string().unwrap_or_default())
})?;
}
Ok(CallbackReturn::Return)
})
}