【发布时间】:2019-12-04 22:41:15
【问题描述】:
我正在尝试从 Rust 中的 lua 文件中检索表。我在 lua 全局上下文中注册了一个 register_entity 函数,以便数据文件注册它们的表。当 lua 文件被执行并调用 register_entity 函数时,注册的回调在 Rust 中被调用。回调应将传递的表添加到 HashMap 以维护所有实体的集合。
这是一个正在读取的示例 lua 文件。
Goblin = {
glyph: "2"
}
register_entity("Goblin", Goblin)
锈代码
fn load_lua_globals(&self) {
let entities = Arc::new(Mutex::new(HashMap::new()));
self.lua.context(|lua_ctx| {
let register_entity = {
let entities = Arc::clone(&entities);
let register_entity = lua_ctx.create_function(
move |_, (name, table): (String, Table)| {
entities.lock().unwrap().insert(name, table);
Ok(())
}).unwrap();
};
lua_ctx.globals().set("register_entity", register_entity).unwrap();
});
}
}
这是错误。
error[E0277]: `*mut rlua::ffi::lua_State` cannot be sent between threads safely
--> src/bin/main.rs:106:47
|
106 | let register_entity = lua_ctx.create_function(
| ^^^^^^^^^^^^^^^ `*mut rlua::ffi::lua_State` cannot be sent between threads safely
|
= help: within `(std::string::String, rlua::Table<'_>)`, the trait `std::marker::Send` is not implemented for `*mut rlua::ffi::lua_State`
= note: required because it appears within the type `rlua::Context<'_>`
= note: required because it appears within the type `rlua::types::LuaRef<'_>`
= note: required because it appears within the type `rlua::Table<'_>`
= note: required because it appears within the type `(std::string::String, rlua::Table<'_>)`
= note: required because of the requirements on the impl of `std::marker::Send` for `hashbrown::raw::RawTable<(std::string::String, rlua::Table<'_>)>`
= note: required because it appears within the type `hashbrown::map::HashMap<std::string::String, rlua::Table<'_>, std::collections::hash_map::RandomState>`
= note: required because it appears within the type `std::collections::HashMap<std::string::String, rlua::Table<'_>>`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Mutex<std::collections::HashMap<std::string::String, rlua::Table<'_>>>`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<std::sync::Mutex<std::collections::HashMap<std::string::String, rlua::Table<'_>>>>`
= note: required because it appears within the type `[closure@src/bin/main.rs:107:21: 112:18 entities:std::sync::Arc<std::sync::Mutex<std::collections::HashMap<std::string::String, rlua::Table<'_>>>>]
【问题讨论】:
-
你不能将
Table存储在外部HashMap中,因为表绑定到lua上下文(真实类型是Table<'lua>)。我建议你使用Context::create_registry_value来存储表格,所以Entities变成HashMap<String, RegistryKey> -
您的问题是关于编译错误,请执行minimal reproducible example