This commit is contained in:
blueloveTH 2024-01-16 10:52:55 +08:00
parent f83dac9252
commit 2fd0732be5
5 changed files with 85 additions and 4 deletions

View File

@ -1,6 +1,6 @@
---
icon: cpu
title: Write bindings
title: Write Bindings
order: 18
---

80
docs/bindings_lua.md Normal file
View File

@ -0,0 +1,80 @@
---
icon: cpu
title: Reuse Lua Bindings
order: 17
---
pkpy provides a lua bridge to reuse lua bindings.
It allows you to run lua code and call lua functions in python.
Add `lua_bridge.hpp` and `lua_bridge.cpp` in [3rd/lua_bridge](https://github.com/blueloveTH/pocketpy/tree/main/3rd/lua_bridge) to your project.
Make sure `lua.h`, `lualib.h` and `lauxlib.h` are in your include path
because `lua_bridge.hpp` needs them.
The lua bridge is based on lua 5.1.5 for maximum compatibility.
lua 5.2 or higher should also work.
### Setup
Use `initialize_lua_bridge(VM*, lua_State*)` to initialize the lua bridge.
This creates a new module `lua` in your python virtual machine.
You can use `lua.dostring` to execute lua code and get the result.
And use `lua.Table()` to create a lua table.
A `lua.Table` instance in python is a dict-like object which provides a bunch of
magic methods to access the underlying lua table.
```python
class Table:
def keys(self) -> list:
"""Return a list of keys in the table."""
def values(self) -> list:
"""Return a list of values in the table."""
def items(self) -> list[tuple]:
"""Return a list of (key, value) pairs in the table."""
def __len__(self) -> int:
"""Return the length of the table."""
def __contains__(self, key) -> bool:
"""Return True if the table contains the key."""
def __getitem__(self, key): ...
def __setitem__(self, key, value): ...
def __getattr__(self, key): ...
def __setattr__(self, key, value): ...
```
### Example
```cpp
#include "lua_bridge.hpp"
using namespace pkpy;
int main(){
VM* vm = new VM();
// create lua state
lua_State* L = luaL_newstate();
luaL_openlibs(L);
// initialize lua bridge
initialize_lua_bridge(vm, L);
// dostring to get _G
vm->exec("import lua");
vm->exec("g = lua.dostring('return _G')");
// create a table
vm->exec("t = lua.Table()");
vm->exec("t.a = 1");
vm->exec("t.b = 2");
// call lua function
vm->exec("g.print(t.a + t.b)"); // 3
return 0;
}
```

View File

@ -1,6 +1,6 @@
---
icon: log
title: 'Cheat sheet'
title: 'Cheatsheet'
order: 22
---

View File

@ -1,7 +1,7 @@
---
icon: book
order: -5
label: Coding style guide
label: Coding Style Guide
---
# Coding Style Guide

View File

@ -1,2 +1,3 @@
icon: rocket
order: 20
label: Quick Start