The State Management module provides powerful persistent state capabilities with atomic operations, distributed locks, and TTL (Time To Live) functionality. All data is stored locally using SQLite with WAL mode for maximum performance and reliability.
-- Set valuesstate.set("app_version","v1.2.3")state.set("user_count",1000)state.set("config",{debug=true,max_connections=100})-- Get valueslocalversion=state.get("app_version")localcount=state.get("user_count")localconfig=state.get("config")-- Get with default valuelocaltheme=state.get("ui_theme","dark")-- Check existenceifstate.exists("app_version")thenlog.info("App version is configured")end-- Delete keystate.delete("old_key")
-- Set with TTL (60 seconds)state.set("session_token","abc123",60)-- Set TTL for existing keystate.set_ttl("user_session",300)-- 5 minutes-- Check remaining TTLlocalttl=state.get_ttl("session_token")log.info("Token expires in "..ttl.." seconds")
-- Add items to liststate.list_push("deployment_queue",{app="frontend",version="v2.1.0",environment="staging"})-- Check list sizelocalqueue_size=state.list_length("deployment_queue")log.info("Items in queue: "..queue_size)-- Process list (pop removes last item)whilestate.list_length("deployment_queue")>0dolocaldeployment=state.list_pop("deployment_queue")log.info("Processing deployment: "..deployment.app)-- Process deployment...end
-- Try to acquire lock (no waiting)locallock_acquired=state.try_lock("deployment_lock",30)-- 30 seconds TTLiflock_acquiredthen-- Critical workstate.unlock("deployment_lock")end-- Lock with wait and timeoutlocalacquired=state.lock("database_migration",60)-- wait up to 60sifacquiredthen-- Execute migrationstate.unlock("database_migration")end-- Critical section with automatic lock managementstate.with_lock("critical_section",function()log.info("Executing critical operation...")-- Update global counterlocalcounter=state.increment("global_counter",1)-- Update timestampstate.set("last_operation",os.time())log.info("Critical operation completed - counter: "..counter)-- Lock is automatically released when function returnsreturn"operation_success"end,15)-- 15 second timeout
functioncheck_rate_limit(identifier,max_requests,window_seconds)localkey="rate_limit:"..identifierlocalcurrent_count=state.get(key,0)ifcurrent_count>=max_requeststhenreturnfalse,"Rate limit exceeded"end-- Increment counterifcurrent_count==0then-- First request in windowstate.set(key,1,window_seconds)else-- Increment existing counterstate.increment(key,1)endreturntrue,"Request allowed"end-- Usage in tasksModernDSLs={api_tasks={tasks={make_api_call={command=function()localallowed,msg=check_rate_limit("api_calls",100,3600)-- 100 calls/hourifnotallowedthenlog.error(msg)returnfalse,msgend-- Make API calllog.info("Making API call...")returntrue,"API call completed"end}}}}