Storing a func. (in GameLogic) that uses external modules?

What I’d like to do is define a bunch of functions once, store them in the GameLogic module, and be able to access them from anywhere. It works as long as the function doesn’t use any external modules, like Math or GameLogic.

Check out the example file here. Press ‘P’ in the 3d window to run and ‘A’ to run the function stored in GameLogic.

Can any python experts out there tell me what I’m doing wrong? Thanks.

Another thread on this can be found here

I’m not a python expert, so I can’t really say why this doesn’t work. but it seems to me since only the function is called and not the import of the module, it doesn’t know about sqrt when called from the other script. You would think that maybe adding the module import to the function would work, but for some reason even most(?) builtin functions are not callable.
The only way I can think of to make this work is to import the module in the calling script and pass it as an argument to the root() function:


# Call script
import math
...
print GameLogic.root(math, x)

and change the root function in the define script to something like:


def root(mathmodule, x):
	return mathmodule.sqrt(x)

if you only need the sqrt function however, the simplest solution is to just use ** instead, no math module needed:


def root(x):
	return x**0.5

Thank you very much, eeshlo! :smiley: Works like a charm!

The real goal of this is to have my game characters create instances of the proper classes once at startup and store them (in GameLogic) in a dictionary. From there I can loop through the dictionary and run their update method. Hmm, did that make any sense? :slight_smile:

Anyways, thanks again!