Skip to main content

nil_lua/
script.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use crate::Lua;
5use crate::error::Result;
6use serde::{Deserialize, Serialize};
7use std::ffi::OsStr;
8use std::path::PathBuf;
9use tokio::fs;
10
11#[derive(Clone, Debug, Deserialize, Serialize)]
12#[serde(rename_all = "camelCase")]
13pub struct Script {
14  pub name: String,
15  pub chunk: String,
16  pub path: PathBuf,
17}
18
19impl Script {
20  pub async fn load(path: PathBuf) -> Result<Self> {
21    let chunk = fs::read_to_string(&path).await?;
22    let name = path
23      .file_stem()
24      .and_then(OsStr::to_str)
25      .map(ToOwned::to_owned)
26      .unwrap_or_else(|| String::from("Script"));
27
28    Ok(Self { name, chunk, path })
29  }
30
31  pub async fn execute(&self, lua: &mut Lua) -> Result<()> {
32    lua.execute(&self.chunk).await
33  }
34}