Global Dictionary


(Jaoshua) #1

Hello everyone I was wondering if you guys can help my figure out how to use global dictionary I know that there are actuators and that you put bge.logic.globalDict ()=() but it still isn’t working what am I doing worng
wrong please help


(wkk.py) #2

# globalDict is a Python dictionary, so you do not use parenthesis...
import bge

# I'm placing the reference to the dict into a local variable named "globalDict".
# Its like a shortcut...
globalDict = bge.logic.globalDict

globalDict["MyGlobalVariableName"] = 5 # in place of the "5" you can store any valid Python object

myVar = globalDict["MyGlobalVariableName"] # here you go


(Jaoshua) #3

Thank you I understand now


(Daedalus_MDW) #4

there is no good reason to use a variable.

globalDict = {}

this will not clear out the logic.globalDict as expected. it will reassign your local variable to a new dictionary object.

for someone new, this could be wildly confusing.

if you want to save some typing, then:

from bge import logic, events, constraints #some common ones

logic.globalDict["Key"] = "Something"

(Rickyx) #5

Clever gem!


(Monster) #6

The attribute bge.logic.globalDict is a build-in container with the sole purpose to hold data in conjunction with the save and the load actuators.

There is no need to use it for any other purposes (as sometimes advised). When you use this bge.logic.globalDict for other purposes, you can’t use the save and load actuators anymore.

You might think that you need such a container to hold your game business model. Why you need exactly that? You can create your own container (as Daedalus_MDW showed). Keep it in any module you like:

gameModel.py


model = {}

demo.py


from gameModel import model

model["last position"] = owner.worldPosition.copy()

Modules are singletons. That means when you import gameModel you get the same model within the same game session.

As you see this is not predefined. You need to build your own dictionary (once).

{} creates a new dictionary. It does not clear an existing one.

This means “myDictionay = {}” creates a new dictionary and assigns it to the variable (which replaces any previous content). It is no clearing operation even when the effect means the previous content is not available via that variable anymore.

To clear a dictionary (including bge.logic.globalDict) use the clear() function:


bge.logic.globalDict.clear()