From 6122ac7926ddd93de7641198fa3ea14e81c20ae2 Mon Sep 17 00:00:00 2001 From: Condorra Date: Wed, 6 Nov 2024 21:48:04 +1100 Subject: [PATCH] Implement storage feature - save state variables locally. --- src/lua_engine.rs | 4 +++- src/lua_engine/storage.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/lua_engine/storage.rs diff --git a/src/lua_engine.rs b/src/lua_engine.rs index 2d09f97..6c7b4fc 100644 --- a/src/lua_engine.rs +++ b/src/lua_engine.rs @@ -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 { @@ -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"); diff --git a/src/lua_engine/storage.rs b/src/lua_engine/storage.rs new file mode 100644 index 0000000..6c4f294 --- /dev/null +++ b/src/lua_engine/storage.rs @@ -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) + }) +}