Using an imported module in a function stored in GameLogic??

Wow, awfully long Subject there… Anyways, my situation is I have a few complex functions I’m going to be calling over and over again from different scripts, so I figure it’d be faster and easier to store them in GameLogic rather than define them each time a script is run.

The problem is I can’t seem to use any imported modules in a function stored within GameLogic. A simplified example:

This script is run at startup to add the functions to GameLogic:

from math import sqrt

def double(x):
   return x*2

def root(x):
   return sqrt(x)

GameLogic.double = double
GameLogic.root = root

…and this script actually calls the functions:

x = 16.0

print GameLogic.double(x)     #--- To be sure the functions are working
print GameLogic.root(x)

but running it gives me the following output:

Traceback (most recent call last):
  File "Call", line 6, in ?
  File "Define", line 5, in root
NameError: global name 'sqrt' is not defined

It can’t find the square root function I imported. :frowning: I’ve tried importing it in the script that calls the function and even tried importing it within the function before “return sqrt(x)”. No dice. Can anyone tell me if it’s possible to use imported modules in functions like this? Thanks!

did you try math.sqrt instead of requiring on sqrt being known as math.sqrt?

Hi, I’m not sure I understand what you’re saying about math.sqrt. I also tried:

import math 

def root(x): 
   return math.sqrt(x)

GameLogic.root = root

and it still gave me an error when I tried to run the function. Is this what you meant or am I on the wrong track? :slight_smile: Thanks again

PS, I’ve uploaded a tiny blend file showing my problem:

I haven’t tried that, but i think You have to use Classes to do such Things.

Good tip, I’ll give it a try. Thanks! :slight_smile:

Hmm, just tried putting the functions in a class and calling them through an instance of that class. Simple functions worked fine, but ones with sqrt still gave:

NameError: global name 'sqrt' is not defined

Maybe it’s a limitation of GameEngine python? :-? I’ll try asking in the Python & Plugins forum, see if anyone there has had this problem. Thanks for your help, guys! :slight_smile:

I’m sure not many people have had this problem, but to anyone interested, eeshlo gave a nice solution.

Just trying to wrap up this old thread and make it useful ;).