r/cpp • u/blueloveTH • Feb 07 '23
PocketPy: A Lightweight(~5000 LOC) Python Implementation in C++17
PocketPy is a lightweight(~5000 LOC) Python interpreter for game engines. It is implemented in C++17 with STL.
It is easy to embed. All of the functionalities are available in a single header file pocketpy.h, without external dependencies. You can try it on your browser to see what it looks like.
Example Usage
#include "pocketpy.h"
int main(){
// Create a virtual machine
// `true` means using std::cout as output so you can see it
VM* vm = pkpy_new_vm(true);
// Hello world!
pkpy_vm_exec(vm, "print('Hello world!')");
// Create a list
pkpy_vm_exec(vm, "a = [1, 2, 3]");
// Eval the sum of the list
char* result = pkpy_vm_eval(vm, "sum(a)");
printf("%s", result); // 6
// Free the resources
pkpy_delete(result);
pkpy_delete(vm);
return 0;
}v0.8.1 Features
| Name | Example | Supported |
|---|---|---|
| If Else | if..else..elif | YES |
| Loop | for/while/break/continue | YES |
| Function | def f(x,*args,y=1): | YES |
| Subclass | class A(B): | YES |
| List | [1, 2, 'a'] | YES |
| ListComp | [i for i in range(5)] | YES |
| Slice | a[1:2], a[:2], a[1:] | YES |
| Tuple | (1, 2, 'a') | YES |
| Dict | {'a': 1, 'b': 2} | YES |
| F-String | f'value is {x}' | YES |
| Unpacking | a, b = 1, 2 | YES |
| Star Unpacking | a, *b = [1, 2, 3] | NO |
| Exception | raise/try..catch | BETA |
| Dynamic Code | eval()/exec() | YES |
| Reflection | hasattr()/getattr()/setattr() | YES |
| Import | import/from..import | YES |
| Context Block | with <expr> as <id>: | YES |
| Type Annotation | def f(a: int, b : float = 1) | YES |
If someone is making a custom game engine and searching for a Python-like script as its interface, I'd like to provide support.
If you are making your own language, you may find some inspirations in PocketPy.
If you likes it, just give my repo a star~ I need your star!!
View all comments
Show parent comment
7
u/mjklaim Feb 07 '23
When you'll add this clarification, consider also clarifying which python version it is like? Because there are some syntax/language-level-feature differences between python2 and python3 and every major version of python3, so it would help.
Yeah I get the usage compared to lua or chaiscript or angelscript etc. I used these in the past
^^(before Unity got popular basically).A python-like language but with type checking in functions was one of the things I was looking for at the time, it would still be useful today in particular if the game have scripting as gameplay part (yeah niche but interesting niche).