more work on the lua stuff

This commit is contained in:
Luuk van Oijen
2023-11-14 09:53:46 +01:00
parent e781bbac8e
commit 1c21298351
5 changed files with 36 additions and 16 deletions

View File

@@ -1,13 +1,18 @@
print("test from lua")
print("Player count: " .. MP.GetPlayerCount())
function onPluginLoaded2()
function onPluginLoaded()
print("HI!")
end
function onPlayerAuthenticated2(name)
function onPlayerAuthenticated(name)
print("hi welcome mista " .. name)
print("current players:")
for id, name in pairs(MP.GetPlayers()) do
print("- [" .. id .. "]" .. name)
end
end
MP.RegisterEventHandler("onPluginLoaded", "onPluginLoaded2")
MP.RegisterEventHandler("onPlayerAuthenticated", "onPlayerAuthenticated2")
MP.RegisterEventHandler("onPluginLoaded", "onPluginLoaded")
MP.RegisterEventHandler("onPlayerAuthenticated", "onPlayerAuthenticated")

View File

@@ -211,6 +211,9 @@ impl Client {
})?;
debug!("user_data: {:?}", user_data);
self.info = Some(user_data);
// self.write_packet(Packet::Raw(RawPacket::from_code('S')))
// .await?;
} else {
self.kick(
"Client never sent public key! If this error persists, try restarting your game.",

View File

@@ -296,7 +296,15 @@ impl Server {
.username
.clone();
info!("Welcome {name}!");
joined_names.push(name);
joined_names.push(name.clone());
let arg = Argument::String(name);
for plugin in &self.plugins {
let (tx, rx) = tokio::sync::oneshot::channel();
plugin.send_event(PluginBoundPluginEvent::CallEventHandler((ScriptEvent::OnPlayerAuthenticated, vec![arg.clone()], Some(tx)))).await;
// TODO: This never returns??
let res = rx.await.unwrap_or(Argument::Number(-1f32));
println!("res: {:?}", res);
}
self.clients.push(clients_incoming_lock.swap_remove(i));
}
trace!("Accepted incoming clients!");
@@ -309,11 +317,11 @@ impl Server {
// it a non-issue I think.
tokio::select! {
_ = self.process_udp() => {},
_ = tokio::time::sleep(tokio::time::Duration::from_millis(1)) => {},
_ = tokio::time::sleep(tokio::time::Duration::from_nanos(1_000)) => {},
};
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_millis(1)) => {},
_ = tokio::time::sleep(tokio::time::Duration::from_nanos(1_000)) => {},
_ = self.process_tcp() => {},
};
@@ -361,7 +369,7 @@ impl Server {
debug!("event: {:?}", event);
// TODO: Error handling (?)
match event {
ServerBoundPluginEvent::PluginLoaded => plugin.send_event(PluginBoundPluginEvent::CallEventHandler((ScriptEvent::OnPluginLoaded, Vec::new()))).await,
ServerBoundPluginEvent::PluginLoaded => plugin.send_event(PluginBoundPluginEvent::CallEventHandler((ScriptEvent::OnPluginLoaded, Vec::new(), None))).await,
ServerBoundPluginEvent::RequestPlayerCount(responder) => { let _ = responder.send(PluginBoundPluginEvent::PlayerCount(self.clients.len())); }
ServerBoundPluginEvent::RequestPlayers(responder) => {
let mut players = HashMap::new();

View File

@@ -133,7 +133,7 @@ impl Backend for BackendLua {
Ok(())
}
fn call_event_handler(&mut self, event: ScriptEvent, args: Vec<Argument>) {
fn call_event_handler(&mut self, event: ScriptEvent, args: Vec<Argument>, resp: Option<oneshot::Sender<Argument>>) {
let event_name = match event {
ScriptEvent::OnPluginLoaded => "onPluginLoaded",
ScriptEvent::OnPlayerAuthenticated => "onPlayerAuthenticated",
@@ -152,8 +152,12 @@ impl Backend for BackendLua {
Argument::Number(f) => Some(Value::Number(f as f64)),
}
}).filter(|v| v.is_some());
if let Err(e) = func.call::<_, ()>(Variadic::from_iter(mapped_args)) {
error!("[LUA] {}", e);
match func.call::<_, Option<f32>>(Variadic::from_iter(mapped_args)) {
Ok(res) => if let Some(resp) = resp { resp.send(Argument::Number(res.unwrap_or(-1f32))).expect("Failed to send!"); } else {}
Err(e) => {
error!("[LUA] {}", e);
if let Some(resp) = resp { resp.send(Argument::Number(-1f32)).expect("Failed to send!"); } else {}
},
}
}
}

View File

@@ -13,12 +13,12 @@ pub trait Backend: Send {
fn load(&mut self, code: String) -> anyhow::Result<()>;
fn load_api(&mut self, tx: Arc<Sender<ServerBoundPluginEvent>>) -> anyhow::Result<()>;
fn call_event_handler(&mut self, event: ScriptEvent, args: Vec<Argument>);
fn call_event_handler(&mut self, event: ScriptEvent, args: Vec<Argument>, resp: Option<oneshot::Sender<Argument>>);
}
// TODO: This is quite focused on Lua right now, perhaps in the future we want to modify this list
// to be more versatile?
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum Argument {
String(String),
Boolean(bool),
@@ -33,7 +33,7 @@ pub enum ScriptEvent {
#[derive(Debug)]
pub enum PluginBoundPluginEvent {
CallEventHandler((ScriptEvent, Vec<Argument>)),
CallEventHandler((ScriptEvent, Vec<Argument>, Option<oneshot::Sender<Argument>>)),
PlayerCount(usize),
Players(HashMap<u8, String>),
@@ -72,8 +72,8 @@ impl Plugin {
loop {
if let Some(message) = pb_rx.blocking_recv() {
match message {
PluginBoundPluginEvent::CallEventHandler((event, args)) => {
backend.call_event_handler(event, args);
PluginBoundPluginEvent::CallEventHandler((event, args, resp)) => {
backend.call_event_handler(event, args, resp);
},
_ => {},
}