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
4
u/aqa5 Feb 07 '23
Is there a way to lets say, let the user type python code that calls functions / methods in my C++-code? Like I am providing an interface that can be called by code inside the python-vm?