Skip to main content

nil_lua/
lib.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![doc(html_favicon_url = "https://nil.dev.br/favicon.png")]
6
7pub mod client;
8pub mod error;
9pub mod script;
10
11use client::ClientUserData;
12use error::Result;
13use mlua::{LuaOptions, StdLib};
14use nil_client::Client;
15use std::sync::Arc;
16use tokio::sync::RwLock;
17
18pub struct Lua(mlua::Lua);
19
20#[bon::bon]
21impl Lua {
22  #[builder]
23  pub fn new(
24    #[builder(start_fn)] client: &Arc<RwLock<Client>>,
25    #[builder(default = StdLib::ALL_SAFE)] libs: StdLib,
26  ) -> Result<Self> {
27    let lua = mlua::Lua::new_with(libs, LuaOptions::default())?;
28
29    let globals = lua.globals();
30    let client_data = ClientUserData::new(Arc::clone(client));
31    globals.set("client", lua.create_userdata(client_data)?)?;
32
33    Ok(Self(lua))
34  }
35
36  pub async fn execute(&mut self, chunk: &str) -> Result<()> {
37    self
38      .0
39      .load(chunk)
40      .exec_async()
41      .await
42      .map_err(Into::into)
43  }
44}
45
46/// Executes a Lua chunk with the given client.
47pub async fn execute(client: &Arc<RwLock<Client>>, chunk: &str) -> Result<()> {
48  Lua::builder(client)
49    .libs(StdLib::ALL_SAFE)
50    .build()?
51    .execute(chunk)
52    .await
53}