Initial commit, tables, functions

This commit is contained in:
SeanOMik 2024-01-21 22:53:53 -05:00
commit 3d61349bf7
Signed by: SeanOMik
GPG Key ID: FEC9E2FC15235964
10 changed files with 861 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target
/.vscode
!/.vscode/launch.json

45
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,45 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'lua-ffi'",
"cargo": {
"args": [
"build",
"--bin=lua-ffi",
"--package=lua-ffi"
],
"filter": {
"name": "lua-ffi",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in executable 'lua-ffi'",
"cargo": {
"args": [
"test",
"--no-run",
"--bin=lua-ffi",
"--package=lua-ffi"
],
"filter": {
"name": "lua-ffi",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}

115
Cargo.lock generated Normal file
View File

@ -0,0 +1,115 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "cc"
version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
dependencies = [
"libc",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cstr"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8aa998c33a6d3271e3678950a22134cd7dd27cef86dee1b611b5b14207d1d90b"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "libc"
version = "0.2.152"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13e3bf6590cbc649f4d1a3eefc9d5d6eb746f5200ffb04e5e142700b8faa56e7"
[[package]]
name = "lua-ffi"
version = "0.1.0"
dependencies = [
"cstr",
"mlua-sys",
"thiserror",
]
[[package]]
name = "mlua-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4655631a02e3739d014951291ecfa08db49c4da3f7f8c6f3931ed236af5dd78e"
dependencies = [
"cc",
"cfg-if",
"pkg-config",
]
[[package]]
name = "pkg-config"
version = "0.3.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2900ede94e305130c13ddd391e0ab7cbaeb783945ae07a279c268cb05109c6cb"
[[package]]
name = "proc-macro2"
version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"

11
Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "lua-ffi"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
cstr = "0.2.11"
mlua-sys = { version = "0.5.0", features = ["lua54"] }
thiserror = "1.0.56"

7
LICENSE Normal file
View File

@ -0,0 +1,7 @@
Copyright © 2024 SeanOMik
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

169
src/function.rs Normal file
View File

@ -0,0 +1,169 @@
use std::ffi::CStr;
use crate::{LuaRef, FromLuaStack, State, PushToLuaStack};
use mlua_sys as lua;
pub struct Function<'a> {
state: &'a State,
lref: LuaRef
}
impl<'a> FromLuaStack<'a> for Function<'a> {
unsafe fn from_lua_stack(state: &'a crate::State) -> crate::Result<Self> {
Ok(Self {
state,
lref: LuaRef::from_stack(state)?,
})
}
}
impl<'a> PushToLuaStack for Function<'a> {
unsafe fn push_to_lua_stack(&self, state: &State) -> crate::Result<()> {
self.lref.push_to_lua_stack(state)
}
}
impl<'a> Function<'a> {
pub fn exec<A, R>(&self, args: A) -> crate::Result<R>
where
A: FunctionArgs,
R: FunctionResults<'a>,
{
unsafe {
self.push_to_lua_stack(self.state)?;
args.push_args_to_lua_stack(self.state)?;
let arg_len = args.len() as i32;
let res_len = R::len() as i32;
let s = self.state.state_ptr();
if lua::lua_pcall(s, arg_len, res_len, 0) != 0 {
let s = lua::lua_tostring(s, -1);
let s = CStr::from_ptr(s);
let s = s.to_str().unwrap();
return Err(crate::Error::runtime(s));
}
R::results_from_lua_stack(self.state)
}
}
}
pub trait FunctionArgs {
fn len(&self) -> usize;
fn push_args_to_lua_stack(&self, state: &State) -> crate::Result<()>;
}
impl<'a, T> FunctionArgs for T
where
T: PushToLuaStack,
{
fn len(&self) -> usize {
1
}
fn push_args_to_lua_stack(&self, state: &State) -> crate::Result<()> {
unsafe {
self.push_to_lua_stack(state)?;
}
Ok(())
}
}
pub trait FunctionResults<'a>: Sized {
fn len() -> usize;
fn results_from_lua_stack(state: &'a State) -> crate::Result<Self>;
}
impl<'a> FunctionResults<'a> for () {
fn len() -> usize {
0
}
fn results_from_lua_stack(_state: &'a State) -> crate::Result<Self> {
Ok(())
}
}
impl<'a, T: FromLuaStack<'a>> FunctionResults<'a> for T {
fn len() -> usize {
1
}
fn results_from_lua_stack(state: &'a State) -> crate::Result<Self> {
unsafe { T::from_lua_stack(state) }
}
}
macro_rules! impl_function_arg_tuple {
( $count: expr, $first: tt, $( $name: tt ),+ ) => (
#[allow(non_snake_case)]
impl<$first: PushToLuaStack, $($name: PushToLuaStack,)+> FunctionArgs for ($first, $($name,)+) {
fn len(&self) -> usize {
// this will end up generating $count - 1 - 1 - 1... hopefully the compiler will
// optimize that out
$count
}
fn push_args_to_lua_stack(&self, state: &State) -> crate::Result<()> {
let ($first, $($name,)+) = self;
unsafe {
$first.push_to_lua_stack(state)?;
$( $name.push_to_lua_stack(state)?; )+
}
Ok(())
}
}
impl<'a, $first: FromLuaStack<'a>, $($name: FromLuaStack<'a>,)+> FunctionResults<'a> for ($first, $($name,)+) {
fn len() -> usize {
$count
}
fn results_from_lua_stack(state: &'a State) -> crate::Result<Self> {
Ok(unsafe { ( $first::from_lua_stack(state)?, $( $name::from_lua_stack(state)?, )+ ) })
}
}
impl_function_arg_tuple!( $count - 1, $( $name ),+ );
);
// implements FunctionArgs and FunctionResults for a tuple with a single element
( $count: expr, $only: tt ) => {
#[allow(non_snake_case)]
impl<$only: PushToLuaStack> FunctionArgs for ($only,) {
fn len(&self) -> usize {
1
}
fn push_args_to_lua_stack(&self, state: &State) -> crate::Result<()> {
let (a,) = self;
unsafe {
a.push_to_lua_stack(state)?;
}
Ok(())
}
}
impl<'a, $only: FromLuaStack<'a>> FunctionResults<'a> for ($only,) {
fn len() -> usize {
1
}
fn results_from_lua_stack(state: &'a State) -> crate::Result<Self> {
Ok(unsafe { ( $only::from_lua_stack(state)?, ) })
}
}
};
}
// hopefully 16 is more than enough
// if you have 16 function results, and need more than 16, you NEED help
impl_function_arg_tuple! { 16, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16 }

221
src/main.rs Normal file
View File

@ -0,0 +1,221 @@
use std::{sync::Arc, ffi::CStr};
use lua::{lua_typename, lua_type};
use mlua_sys as lua;
pub mod state;
use state::*;
pub mod table;
use table::*;
pub mod function;
use function::*;
pub mod value;
use value::*;
fn main() -> Result<()> {
let lua = State::new();
lua.expose_libraries(&[StdLibrary::Debug]);
let tbl = lua.create_table()?;
tbl.set("x", 10)?;
let globals = lua.globals()?;
globals.set("X", tbl)?;
lua.execute(r#"
--[[function dump_table(tbl)
for k, v in pairs(tbl) do
if type(v) == "table" then
dump_table(v)
elseif type(v) == "function" then
else
print(k .. "=" .. tostring(v))
end
end
end
for k, v in pairs(_G) do
--print("Found global named " .. k)
if k == "X" then
--dump_table(v)
end
end]]--
print("x is " .. X.x)
cool_num = 50
function say_number(num)
print("I'm lua and I said " .. num)
end
function multiply_print(a, b)
print(a .. " * " .. b .. " = " .. a * b)
end
function multiply_ret(a, b)
return a * b
end
"#).unwrap();
let num = globals.get::<_, i32>("cool_num")?;
assert_eq!(num, 50);
println!("Got number as 50!");
let num = globals.get::<_, Function>("say_number")?;
num.exec::<_, ()>(50)?;
let num = globals.get::<_, Function>("multiply_print")?;
num.exec::<_, ()>((10, 5))?;
let num = globals.get::<_, Function>("multiply_ret")?;
let num: i32 = num.exec::<_, i32>((10, 5))?;
assert_eq!(num, 50);
println!("Did math in lua and got 50!");
Ok(())
}
#[derive(Clone)]
pub struct LuaRef(Arc<i32>);
impl From<i32> for LuaRef {
fn from(value: i32) -> Self {
Self(Arc::new(value))
}
}
impl LuaRef {
/// Creates a reference to what is at the top of the stack.
pub unsafe fn from_stack(state: &State) -> Result<Self> {
let s = state.state_ptr();
let r = lua::luaL_ref(s, lua::LUA_REGISTRYINDEX);
if r == lua::LUA_REFNIL {
Err(Error::Nil)
} else {
Ok(LuaRef::from(r))
}
}
}
impl PushToLuaStack for LuaRef {
unsafe fn push_to_lua_stack(&self, state: &State) -> Result<()> {
let s = state.state_ptr();
unsafe {
state.ensure_stack(1)?;
lua::lua_rawgeti(s, lua::LUA_REGISTRYINDEX, *self.0 as i64);
}
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Lua runtime error: {0}")]
/// An error returned from lua
Runtime(String),
#[error("Ran out of memory when attempting to use `lua_checkstack`")]
/// Ran into a not enough memory error when trying to grow the lua stack.
Oom,
#[error("Ran into a nill value on the stack")]
Nil,
#[error("Unexpected type, expected {0} but got {1}")]
UnexpectedType(String, String)
}
impl Error {
pub fn runtime(msg: &str) -> Self {
Self::Runtime(msg.to_string())
}
pub fn unexpected_type(expected: &str, got: &str) -> Self {
Self::UnexpectedType(expected.to_string(), got.to_string())
}
}
/// A result for use with lua functions
type Result<T> = core::result::Result<T, Error>;
pub trait PushToLuaStack {
unsafe fn push_to_lua_stack(&self, state: &State) -> Result<()>;
}
pub trait FromLuaStack<'a>: Sized {
unsafe fn from_lua_stack(state: &'a State) -> Result<Self>;
}
/// Implements PushToLuaStack for a number
macro_rules! impl_push_to_lua_stack_number {
($ty: ident) => {
impl PushToLuaStack for $ty {
unsafe fn push_to_lua_stack(&self, state: &State) -> Result<()> {
state.ensure_stack(1)?;
lua::lua_pushnumber(state.state_ptr(), *self as f64);
Ok(())
}
}
};
}
impl<'a> FromLuaStack<'a> for i32 {
unsafe fn from_lua_stack(state: &'a State) -> Result<Self> {
let s = state.state_ptr();
if lua::lua_isnumber(s, -1) == 1 {
Ok(lua::lua_tonumber(s, -1) as i32)
} else {
let lua_ty = lua_type(s, -1);
let typec = CStr::from_ptr(lua_typename(s, lua_ty));
let type_str = typec.to_str()
.expect("Type has invalid bytes!");
Err(Error::unexpected_type("Number", type_str))
}
}
}
impl_push_to_lua_stack_number!(i8);
impl_push_to_lua_stack_number!(i16);
impl_push_to_lua_stack_number!(i32);
impl_push_to_lua_stack_number!(i64);
impl_push_to_lua_stack_number!(u8);
impl_push_to_lua_stack_number!(u16);
impl_push_to_lua_stack_number!(u32);
impl_push_to_lua_stack_number!(u64);
impl_push_to_lua_stack_number!(f32);
impl_push_to_lua_stack_number!(f64);
impl PushToLuaStack for String {
unsafe fn push_to_lua_stack(&self, state: &State) -> Result<()> {
state.ensure_stack(1)?;
let s = format!("{}\0", self);
let cstr = s.as_ptr() as *const i8;
lua::lua_pushstring(state.state_ptr(), cstr);
Ok(())
}
}
impl PushToLuaStack for &str {
unsafe fn push_to_lua_stack(&self, state: &State) -> Result<()> {
state.ensure_stack(1)?;
let s = format!("{}\0", self);
let cstr = s.as_ptr() as *const i8;
lua::lua_pushstring(state.state_ptr(), cstr);
Ok(())
}
}

163
src/state.rs Normal file
View File

@ -0,0 +1,163 @@
use core::ffi;
use std::{ptr::NonNull, ffi::{CString, CStr}};
use mlua_sys as lua;
use crate::{Table, Result, Error, LuaRef};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StdLibrary {
Coroutine,
Table,
Io,
Os,
String,
Utf8,
Math,
Debug,
Package,
}
impl StdLibrary {
pub fn lua_name(&self) -> &'static str {
match self {
StdLibrary::Coroutine => lua::LUA_COLIBNAME,
StdLibrary::Table => lua::LUA_TABLIBNAME,
StdLibrary::Io => lua::LUA_IOLIBNAME,
StdLibrary::Os => lua::LUA_OSLIBNAME,
StdLibrary::String => lua::LUA_STRLIBNAME,
StdLibrary::Utf8 => lua::LUA_UTF8LIBNAME,
StdLibrary::Math => lua::LUA_MATHLIBNAME,
StdLibrary::Debug => lua::LUA_DBLIBNAME,
StdLibrary::Package => lua::LUA_LOADLIBNAME,
}
}
pub fn lua_openf(&self) -> unsafe extern "C-unwind" fn(*mut lua::lua_State) -> ffi::c_int {
match self {
StdLibrary::Coroutine => lua::luaopen_coroutine,
StdLibrary::Table => lua::luaopen_table,
StdLibrary::Io => lua::luaopen_io,
StdLibrary::Os => lua::luaopen_os,
StdLibrary::String => lua::luaopen_string,
StdLibrary::Utf8 => lua::luaopen_utf8,
StdLibrary::Math => lua::luaopen_math,
StdLibrary::Debug => lua::luaopen_debug,
StdLibrary::Package => lua::luaopen_package,
}
}
}
#[derive(Default)]
pub struct StdLibraries {
libs: Vec<StdLibrary>
}
impl StdLibraries {
pub fn new() -> Self {
Self::default()
}
pub fn all() -> Self {
todo!()
}
pub fn load(&mut self, lib: StdLibrary) {
self.libs.push(lib)
}
}
impl<const N: usize> From<&[StdLibrary; N]> for StdLibraries {
fn from(value: &[StdLibrary; N]) -> Self {
Self {
libs: value.to_vec(),
}
}
}
pub struct State {
lua: NonNull<lua::lua_State>,
}
impl Drop for State {
fn drop(&mut self) {
unsafe { lua::lua_close(self.lua.as_ptr()); }
}
}
impl State {
pub fn new() -> Self {
Self {
lua: unsafe { NonNull::new_unchecked(lua::luaL_newstate()) }
}
}
pub fn state_ptr(&self) -> *mut lua::lua_State {
self.lua.as_ptr()
}
pub fn execute(&self, text: &str) -> Result<()> {
let text = format!("{}\0", text);
unsafe {
let lua = self.lua.as_ptr();
let text_c = text.as_ptr() as *const ffi::c_char;
if lua::luaL_dostring(lua, text_c) != 0 {
let error_c = CStr::from_ptr(lua::lua_tostring(lua, -1));
let error_str = error_c.to_str()
.expect("Error bytes are invalid!");
return Err(Error::runtime(error_str));
}
}
Ok(())
}
pub fn expose_libraries<L: Into<StdLibraries>>(&self, libs: L) {
let lua = self.lua.as_ptr();
unsafe {
let base = "_G".as_ptr() as *const i8;
lua::luaL_requiref(lua, base, lua::luaopen_base, 1);
assert_eq!(lua::lua_tonumber(lua, -1), 0.0); // ensure that loading base worked
lua::lua_pop(lua, 1);
}
for lib in libs.into().libs.into_iter() {
let name = CString::new(lib.lua_name())
.expect("Invalid library name!");
let openf = lib.lua_openf();
unsafe {
assert_eq!(lua::lua_gettop(lua), 0);
lua::luaL_requiref(lua, name.as_ptr(), openf, 1);
assert_eq!(lua::lua_gettop(lua), 1);
assert_eq!(lua::lua_tonumber(lua, -1), 0.0);
lua::lua_pop(lua, 1);
}
}
}
pub fn create_table(&self) -> Result<Table> {
Table::new(self)
}
/// This called `lua_checkstack` and returns a result.
///
/// The result will be Ok if the stack has space for `n` values.
pub unsafe fn ensure_stack(&self, n: i32) -> Result<()> {
if lua::lua_checkstack(self.state_ptr(), n) == 0 {
Err(Error::Oom)
} else {
Ok(())
}
}
pub fn globals(&self) -> Result<Table> {
unsafe {
let s = self.state_ptr();
lua::lua_rawgeti(s, lua::LUA_REGISTRYINDEX, lua::LUA_RIDX_GLOBALS);
Table::with_ref(self, LuaRef::from_stack(self)?)
}
}
}

89
src/table.rs Normal file
View File

@ -0,0 +1,89 @@
use mlua_sys as lua;
use crate::{State, Result, PushToLuaStack, LuaRef, FromLuaStack};
pub struct Table<'a> {
state: &'a State,
lref: LuaRef,
}
impl<'a> Table<'a> {
pub fn new(state: &'a State) -> Result<Self> {
let lref = unsafe {
state.ensure_stack(1)?;
let s = state.state_ptr();
lua::lua_newtable(s);
LuaRef::from_stack(state)?
};
Ok(Self {
state,
lref,
})
}
pub fn with_ref(state: &'a State, lua_ref: LuaRef) -> Result<Self> {
let s = state.state_ptr();
unsafe {
lua_ref.push_to_lua_stack(state)?;
if lua::lua_istable(s, -1) == 0 {
panic!("Index is not a table")
}
lua::lua_pop(s, -1);
}
Ok(Self {
state,
lref: lua_ref,
})
}
pub fn set<K, V>(&self, key: K, val: V) -> Result<()>
where
K: PushToLuaStack,
V: PushToLuaStack
{
let s = self.state.state_ptr();
unsafe {
self.state.ensure_stack(3)?;
self.lref.push_to_lua_stack(self.state)?;
key.push_to_lua_stack(self.state)?;
val.push_to_lua_stack(self.state)?;
lua::lua_settable(s, -3);
lua::lua_pop(self.state.state_ptr(), -1);
}
Ok(())
}
pub fn get<K, V>(&'a self, key: K) -> Result<V>
where
K: PushToLuaStack,
V: FromLuaStack<'a>,
{
let s = self.state.state_ptr();
unsafe {
self.lref.push_to_lua_stack(self.state)?;
key.push_to_lua_stack(self.state)?;
lua::lua_gettable(s, -2); // table[key] is at top of stack
V::from_lua_stack(self.state)
}
//todo!()
}
}
impl<'a> PushToLuaStack for Table<'a> {
unsafe fn push_to_lua_stack(&self, state: &State) -> Result<()> {
// no need to ensure stack, the LuaRef does it for us
self.lref.push_to_lua_stack(state)?;
Ok(())
}
}

38
src/value.rs Normal file
View File

@ -0,0 +1,38 @@
use crate::{Function, Table, PushToLuaStack};
use mlua_sys as lua;
pub enum Value<'a> {
Number(f64),
String(String),
Function(Function<'a>),
Table(Table<'a>),
}
impl<'a> PushToLuaStack for Value<'a> {
unsafe fn push_to_lua_stack(&self, state: &crate::State) -> crate::Result<()> {
let s = state.state_ptr();
match self {
Value::Number(n) => {
state.ensure_stack(1)?;
lua::lua_pushnumber(s, *n);
},
Value::String(s) => {
state.ensure_stack(1)?;
let s = format!("{}\0", s);
let cstr = s.as_ptr() as *const i8;
lua::lua_pushstring(state.state_ptr(), cstr);
}
Value::Function(f) => {
f.push_to_lua_stack(state)?;
},
Value::Table(t) => {
t.push_to_lua_stack(state)?;
}
}
Ok(())
}
}