From BlenderWiki

< Doc:Tutorials | Extensions | Python | BSoD
Revision as of 14:21, 4 April 2009 by Mindrones (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Blender Summer of Documentation: Contents | Manual | Blender Version 2.41

[edit] Storing and retrieving persistent data in scripts.

Whenever a Blender script runs, it has no memory of anything that has happened before. When the script exits, nothing is saved. If we want to communicate information between one run of a script or between two different scripts, we need some way to create persistent data. The way we do this is the Registry module.

The Registry module is a persistent dictionary of dictionaries. Said another way, we can create a Python dictionary, stuff it with whatever data we find useful and store it in the Registry by a unique name.

Note
Read about dictionaries in the Python tutorial here.
Read about the Registry module in the BPy API documentation here

In this example, we create a dictionary called myDict with one name/value pair called 'greeting'. Each time the script runs, it changes the greeting from 'hello' to 'goodbye' and prints a message.

This may look complicated, but we can break it down like this:

First we check if our dictionary is in the registry.

if not in the dictionary, we create it
otherwise
  print the greeting and swap goodbye for hello 
    or vice versa

You can uncomment the last line and run the script to clear our data from the Registry.

[edit] Program: Using Persistent Data

import Blender as B

# is our dictionary in the registry?

myDict= B.Registry.GetKey('Greetings')

if not myDict:  # our dictionary does NOT exist.  must create
	myDict = {}
	myDict['greeting'] = 'hello'
	print 'creating dictionary!'
else:
	if 'greeting' not in myDict:
		myDict['greeting'] = 'hello'
		print 'no greeting found!'
	else:
		print myDict['greeting'], 'World!'
		# set new greeting.  flip/flop between hello & goodbye
		if myDict['greeting'] == 'hello':
			myDict['greeting'] = 'goodbye'
		else:
			myDict['greeting'] = 'hello'

# store our dictionary
B.Registry.SetKey('Greetings', myDict)

# uncomment this line to remove our dictionary
#B.Registry.RemoveKey('Greetings')