Skip to content
This repository has been archived by the owner on Mar 9, 2020. It is now read-only.

germangb/lua-rs

Repository files navigation

Lua rust

Build Status

(WIP) Rust wrapper around the Lua C API.

Documentation

Examples

# Run an interactive lua shell ([FILE] is optional)
$ cargo run --example lua [FILE]

Hello World

extern crate lua;

let mut state = lua::State::new();
state.open_libs();

state.eval("print ('hello world')").unwrap();

Functions

Types that implement the Function trait can be used as lua functions:

extern crate lua;

use lua::{Function, Index};

// A Type for a function that returns the length of a string
enum StringLength {}

impl Function for StringLength {
    type Error = lua::Error;

    fn call(state: &mut lua::State) -> Result<usize, Self::Error> {
        let length = state.get(Index::Bottom(1)).map(|s: &str| s.len())?;
        state.push(length)?;
        Ok(1)
    }
}

let mut state = lua::State::new();

state.push_function::<StringLength>().unwrap();
state.set_global("length");

state.eval("len = length('hello world')").unwrap(); // len = 11

Custom Userdata

Types that implements the UserData trait can be used as userdata. When a type is moved into the stack, the State becomes its owner and will eventually be dropped by the garbage collector.

For a more complete example, including setting up metamethods, see this example.

extern crate lua;

use lua::{UserData, Index};

#[derive(Debug)]
struct Foo {
    bar: Vec<i32>,
    baz: String,
}

impl UserData for Foo {
    // An identifier, unique to the Type
    const METATABLE: &'static str = "Example.foo";
}

let mut state = lua::State::new();

state.push_udata(Foo {
    bar: vec![0; 16],
    baz: String::from("Hello world!"),
}).unwrap();

// Get a reference to the stack
let foo: &Foo = state.get_udata(Index::TOP).unwrap();

// To get a mutable reference, use this instead:
// let foomut: &mut Foo = state.get_udata_mut(Index::TOP).unwrap();

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published