Skip to content

Instantly share code, notes, and snippets.

@codefionn
Created June 5, 2022 19:46
Show Gist options
  • Select an option

  • Save codefionn/16250fa134b5c0067e8fbad783f40e49 to your computer and use it in GitHub Desktop.

Select an option

Save codefionn/16250fa134b5c0067e8fbad783f40e49 to your computer and use it in GitHub Desktop.
Use Lua as an Bevy-Engine asset
use bevy::asset::{AssetLoader, BoxedFuture, LoadContext, LoadedAsset};
use mlua::prelude::*;
use std::marker::PhantomData;
pub trait LuaFile: Sized {
fn new(lua: std::sync::Mutex<Lua>) -> Self;
}
/// Loads Text as an asset
pub struct LuaFileAssetLoader<A: bevy::asset::Asset + LuaFile> {
pub extensions: Vec<&'static str>,
pub _marker: PhantomData<A>
}
impl<A: bevy::asset::Asset + LuaFile> Default for LuaFileAssetLoader<A> {
fn default() -> Self {
Self {
extensions: vec!["lua"],
_marker: PhantomData::default()
}
}
}
impl<A: bevy::asset::Asset + LuaFile> AssetLoader for LuaFileAssetLoader<A> {
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<(), anyhow::Error>> {
return Box::pin(async move {
let code = String::from_utf8(Vec::from(bytes))?;
let lua = Lua::new();
lua.load(&code)
.exec()
.expect("Expected correct lua language file");
lua.gc_stop();
let lua = std::sync::Mutex::new(lua);
load_context.set_default_asset(LoadedAsset::new(A::new(lua)));
Ok(())
});
}
fn extensions(&self) -> &[&str] {
return &self.extensions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment