mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-04-06 07:46:06 +00:00
very early version of plugin system
This commit is contained in:
38
src/server/plugins/backend_lua.rs
Normal file
38
src/server/plugins/backend_lua.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use super::Backend;
|
||||
use mlua::prelude::*;
|
||||
|
||||
pub struct BackendLua {
|
||||
lua: Lua,
|
||||
}
|
||||
|
||||
impl BackendLua {
|
||||
pub fn new() -> Self {
|
||||
let lua = Lua::new();
|
||||
|
||||
Self {
|
||||
lua,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for BackendLua {
|
||||
fn load(&mut self, code: String) -> anyhow::Result<()> {
|
||||
self.lua.load(code).exec().map_err(|e| { error!("[LUA] {:?}", e); e })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_api(&mut self) -> anyhow::Result<()> {
|
||||
let print_fn = self.lua.create_function(|_lua, (msg,): (String,)| {
|
||||
info!("[LUA] {}", msg);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let api = self.lua.create_table()?;
|
||||
|
||||
api.set("print", print_fn)?;
|
||||
|
||||
self.lua.globals().set("MP", api)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
51
src/server/plugins/mod.rs
Normal file
51
src/server/plugins/mod.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
pub mod backend_lua;
|
||||
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::sync::mpsc::{self, Sender, Receiver};
|
||||
|
||||
pub trait Backend {
|
||||
fn load(&mut self, code: String) -> anyhow::Result<()>;
|
||||
fn load_api(&mut self) -> anyhow::Result<()> { Ok(()) }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PluginBoundPluginEvent {
|
||||
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ServerBoundPluginEvent {
|
||||
PluginLoaded,
|
||||
}
|
||||
|
||||
pub struct Plugin {
|
||||
runtime: Runtime,
|
||||
tx: Sender<PluginBoundPluginEvent>,
|
||||
rx: Receiver<ServerBoundPluginEvent>,
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
pub fn new(backend: Box<dyn Backend>) -> Self {
|
||||
let runtime = Runtime::new().expect("Failed to create a tokio Runtime!");
|
||||
let (pb_tx, mut pb_rx) = mpsc::channel(1_000);
|
||||
let (sb_tx, sb_rx) = mpsc::channel(1_000);
|
||||
runtime.spawn(async move {
|
||||
if sb_tx.send(ServerBoundPluginEvent::PluginLoaded).await.is_err() {
|
||||
error!("Plugin communication channels somehow already closed!");
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
if let Some(message) = pb_rx.recv().await {
|
||||
debug!("Received message: {:?}", message);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
Self {
|
||||
runtime,
|
||||
tx: pb_tx,
|
||||
rx: sb_rx,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user