1

I am writing a game engine in Python and the thing is I am not sure how to handle external scripts (think source engine mods, LUA). Every scene, entity in a game can have custom script attached to it, but game engine is not aware of those scripts until the scene is being loaded. For example there could be a script, which would animate game cutscene and that script would be used only in one scene.

So, what i want to know is what's the best way to handle those scripts? I know I could import them with exec or eval, but someone said it's now safe. Why? I could also create some scripting language, which would be parsed during runtime, but I don't see a point in that considering that Python is scripting language itself. Any help would be greatly appreciated.

3 Answers 3

0

You can use __import__() for this. Say your entity has a script attribute that can be either None or the name of a script (that is in a known location, which is on sys.path), you could use the following code to run the main() function from that script:

if entity.script is not None:
    custom_script = __import__(entity.script, globals(), locals(), [], -1)
    custom_script.main()
Sign up to request clarification or add additional context in comments.

Comments

0

Yes, exec and eval are not safe for user-supplied data, like handling expressions or Web input. But if you specifically want to give users the full power of Python, and you understand the risks (users can do anything – erase/read files on the computer, crash Python, enter an infinite loop, etc.), using exec is perfectly fine.

If you trust your game script designer(s), exec away. If the levels can come from random people on the Internet, at least let your players be aware of the risk.

Comments

0

You can run your external script either using by importing it using __import__() or using exec/execfile function. It is nice to know that:

  • import compiles script to byte-code and saves .pyc file at first usage
  • import tries to search for the module and eventually it creates module with its own namespace in contrast to exec/execfile that just executes the code in string/file.
  • it is possible to sandbox your code a bit by mangling with globals builtins during passing globals as parameters to __import__/execfile, although this method is not super safe, see my answer to this question for example.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.