gluau/pluau
GitHub: gluau/pluau
Pluau 是基于 PyO3 的 Luau Python 绑定库,让开发者能在 Python 中安全地执行具备内存和执行时间限制的 Luau 脚本。
Stars: 7 | Forks: 1
# pluau
Pluau 通过 PyO3/Maturin 为 Luau 提供了高级 Python 绑定。
除了 Buffer 支持外,Luau 的所有功能均应得到 pluau 的广泛支持。
## 示例
### 创建 Lua VM 并运行脚本
```
import pluau
lua = pluau.Lua()
lua.set_memory_limit(1 * 1024 * 1024) # Optional: Set memory limit of the created Lua VM to 1MB
func = lua.load_chunk("return 2 + 2", name="example") # You can optionally set env as well to give the chunk its own custom global environment table (_G)
result = func()
print(result) # [4]
```
### 表
```
tab = lua.create_table()
tab.push(123)
tab.set("key1", 456)
# 打印 1 123,随后是 key1 456
for k, v in tab:
print("key", k, v)
print(len(tab)) # 1 (Lua/Luau only considers array part for length operator)
# 设置 metatable
my_metatable = lua.create_table()
tab.set_metatable(my_metatable)
# 在表上设置 readonly 属性(Luau 特有的安全功能)Luau s
tab.readonly = True
# 由于表是 readonly 的,下面的代码现在会报错
tab.set("key2", 789) # errors with "runtime error: attempt to modify a readonly table"
tab.readonly = False # make it writable again
tab.set("key2", 789) # works now
```
### 设置执行时间限制
Luau 提供了中断(interrupts)功能,这是一个在 Luau 代码执行期间周期性调用的回调函数。这可用于实现执行时间限制。
```
import pluau
import time
start_time = time.time()
def interrupt(_: pluau.Lua):
if time.time() - start_time > 1.0: # 1 second limit
return pluau.VmState.Yield
return pluau.VmState.Continue
lua = pluau.Lua()
lua.set_interrupt(interrupt)
func = lua.load_chunk("while true do end", name="infinite_loop")
# 当使用 interrupts 时,函数应该被制作成一个 thread 然后恢复。否则,yield 将导致运行时错误。
thread = lua.create_thread(func)
result = thread.resume() # Resume the thread with no arguments
print(result, thread.status) # Prints [] ThreadState.Resumable after 1 second
```
标签:FFI, Lua, Luau, Maturin, PyO3, Python, Roblox, Rust, 互操作性, 代码执行, 内存限制, 可视化界面, 后端开发, 安全控制, 嵌入式脚本, 库, 应急响应, 执行超时, 无后门, 沙箱, 游戏开发, 生成式AI安全, 网络流量审计, 网络调试, 自动化, 虚拟机, 解释器, 语言绑定, 逆向工具