Global & Private State

In web server environments, scripts are typically stateless and reset with every request. DWScript provides specialized mechanisms to maintain state across requests and share data between concurrent users.

Persistence Mechanisms

These variables are stored in the server's memory and are accessible across different requests. They are ideal for caching, configuration, or application-wide counters.

Type Scope Persistence Use Case
GlobalVars Application-wide Until server restart Shared caches, global settings.
PrivateVars Unit/Library namespaced Until server restart Module-specific data, private counters.

Global Variables (GlobalVars)

GlobalVars are shared across the entire web application. Any script can read or write to any GlobalVar.

  • WriteGlobalVar(name, value [, expire]): Stores a value with optional expiration in seconds.
  • ReadGlobalVar(name): Retrieves a value. Returns Unassigned if it doesn't exist.
  • ReadGlobalVarDef(name, default): Retrieves a value or returns the default.
  • IncrementGlobalVar(name [, amount, expire]): Atomically increments a numeric value (thread-safe).

Private Variables (PrivateVars)

PrivateVars work similarly to GlobalVars but are namespaced to the Unit (Module) in which they are used. This prevents naming collisions between different libraries.

  • WritePrivateVar(name, value [, expire])
  • ReadPrivateVar(name [, default])
  • IncrementPrivateVar(name [, amount, expire]): Atomically increments a numeric value.

Example Usage

The following example demonstrates a simple, thread-safe request counter.

var count : Integer;

// Atomic increment is the safest way to update shared counters
count := IncrementGlobalVar('VisitorCount');

PrintLn('You are visitor number: ' + IntToStr(count));

// Reset for documentation consistency
WriteGlobalVar('VisitorCount', 0);
Result
You are visitor number: 1

Concurrency Warning

Since these variables are shared across all concurrent requests, they are subject to race conditions if multiple scripts try to modify them simultaneously. For complex state management, consider using a database or thread-safe primitives.

On this page