The StateLink is a kind of FreeLink useful for storing key-value pairs in the atomspace. It can be used for maintaining state, as well as setting "properties" on an atom. The StateLink associates a single, unique value for a given key; the keys and values can be any atoms. Creating a new StateLink silently deletes the earlier one from the AtomSpace.
To be precise, the StateLink only allows a single closed value per key; any number of open values are allowed. A "closed term" is an atom that has no free variables in it; an open term does contain free variables. The reason for this distinction is that terms containing VariableNodes are useful for managing GetLinks and PutLinks for manipulating and setting state.
If only one key-value pairing in-total is desired, open or closed, the DefineLink can be used. A related concept is the DeleteLink, which allows exactly zero closed terms, but any number of open terms.
The StateLink also differs from DefineLink in that, whenever a new StateLink is added to the AtomSpace, the old one for that key is automatically deleted. By contrast, the DefineLink will throw an error if such an operation is attempted.
StateLink inherits from UniqueLink, which provides the actual mechanics implementing uniqueness.
Example: simple state
The following sets a "switch" to the "on" position:
StateLink ConceptNode "switch" ConceptNode "on"
If the below is added to the atomspace:
StateLink ConceptNode "switch" ConceptNode "off"
then the "switch" is turned "off"; the StateLink to the "on" position is automatically removed; the atomspace will contain only the link to the "off" position.
A working example is here: /examples/atomspace/state.scm
Example: atom properties
One may associate "properties" with an atom, simply by a judicious use of the StateLink. For example, one can associate a "truthiness" of 0.76 with the Concept "foo" by writing
(StateLink (ListLink (ConceptNode "foo") (PredicateNode "truthiness")) (NumberNode 0.76) )
The key here is simply a concatenation of the atom and the property. A more detailed example is here: /examples/atomspace/property.scm
At this time, the lookup of atom properties is not optimized for speed, but it could be, by caching properties in the StateLink C++ code.