| Crates.io | lua-bind |
| lib.rs | lua-bind |
| version | 0.1.0 |
| created_at | 2025-04-27 08:43:44.07535+00 |
| updated_at | 2025-04-27 08:43:44.07535+00 |
| description | Thread-safe Lua binding system with automatic type registration and dependency injection |
| homepage | |
| repository | https://github.com/wuslin/lua-bind |
| max_upload_size | |
| id | 1650923 |
| size | 68,529 |
一个高性能、线程安全的Rust到Lua的绑定系统,提供自动类型注册和依赖注入功能。
在Cargo.toml中添加:
[dependencies]
lua-bind = { version = "0.1", features = ["async"] } # 按需启用特性
可选特性:
async - 启用异步支持vendored - 静态链接Lua库use lua_bind::{get_lua, register_binding};
#[derive(Default)]
struct MathUtils;
impl mlua::UserData for MathUtils {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method("add", |_, _, (a, b): (i32, i32)| Ok(a + b));
}
}
register_binding!(MathUtils);
fn main() {
let lua = get_lua().unwrap();
lua.load(r#"
print(Rust.MathUtils.add(1, 2)) -- 输出3
"#).exec().unwrap();
}
#[derive(Default)]
struct AsyncApi;
impl mlua::UserData for AsyncApi {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_async_method("fetch", |_, _, url: String| async {
Ok(reqwest::get(&url).await?.text().await?)
});
}
}
#[derive(Serialize, Deserialize)]
struct User {
name: String,
age: u32
}
impl mlua::UserData for User {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method("to_json", |_, this, ()| {
Ok(serde_json::to_string(this)?)
});
}
}
let handles: Vec<_> = (0..4).map(|_| {
thread::spawn(|| {
let lua = get_lua().unwrap();
// 安全并发访问
})
}).collect();
完整API文档见: docs.rs/lua-bind
查看examples/目录获取更多示例:
basic.rs - 基础用法async.rs - 异步交互serialization.rs - 序列化示例cargo run --example basic
cargo run --example async --features test-async
cargo run --example serialization
test-async 只为了适配async案例设计的特性,不建议直接使用欢迎提交Issue和PR!开发前请阅读:
cargo test --all-featurescargo fmt --all本项目采用双重许可: