Skip to content

Commit

Permalink
Add some support for the Lua API
Browse files Browse the repository at this point in the history
  • Loading branch information
paulyoung committed Oct 15, 2023
1 parent 3e54be6 commit 5850579
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod display;
pub mod file;
pub mod geometry;
pub mod graphics;
pub mod lua;
pub mod sound;
pub mod sprite;
pub mod system;
Expand All @@ -18,6 +19,7 @@ use {
display::Display,
file::FileSystem,
graphics::{Graphics, PDRect},
lua::Lua,
sound::Sound,
sprite::{
Sprite, SpriteCollideFunction, SpriteDrawFunction, SpriteManager, SpriteUpdateFunction,
Expand Down Expand Up @@ -48,6 +50,8 @@ impl Playdate {
FileSystem::new(file);
let graphics = unsafe { (*playdate).graphics };
Graphics::new(graphics);
let lua = unsafe { (*playdate).lua };
Lua::new(lua);
let sound = unsafe { (*playdate).sound };
Sound::new(sound)?;
let display = unsafe { (*playdate).display };
Expand Down
45 changes: 45 additions & 0 deletions src/lua.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use {
crate::pd_func_caller,
alloc::string::String,
anyhow::{anyhow, Error},
core::ptr,
crankstart_sys::{ctypes, lua_CFunction},
cstr_core::{CStr, CString},
};

static mut LUA: Lua = Lua(ptr::null_mut());

#[derive(Clone, Debug)]
pub struct Lua(*const crankstart_sys::playdate_lua);

impl Lua {
pub(crate) fn new(file: *const crankstart_sys::playdate_lua) {
unsafe {
LUA = Lua(file);
}
}

pub fn get() -> Self {
unsafe { LUA.clone() }
}

pub fn add_function(&self, f: lua_CFunction, name: &str) -> Result<(), Error> {
let c_name = CString::new(name).map_err(Error::msg)?;
let mut out_err: *const crankstart_sys::ctypes::c_char = ptr::null_mut();
pd_func_caller!((*self.0).addFunction, f, c_name.as_ptr(), &mut out_err)?;
if out_err != ptr::null_mut() {
let err_msg = unsafe { CStr::from_ptr(out_err).to_string_lossy().into_owned() };
Err(anyhow!(err_msg))
} else {
Ok(())
}
}

pub fn get_arg_string(&self, pos: i32) -> Result<String, Error> {
let c_arg_string = pd_func_caller!((*self.0).getArgString, pos as ctypes::c_int)?;
unsafe {
let arg_string = CStr::from_ptr(c_arg_string).to_string_lossy().into_owned();
Ok(arg_string)
}
}
}

0 comments on commit 5850579

Please sign in to comment.