Struct hlua::Lua

source ·
pub struct Lua<'lua> { /* private fields */ }
Expand description

Main object of the library.

The lifetime parameter corresponds to the lifetime of the content of the Lua context.

§About panic safety

This type isn’t panic safe. This means that if a panic happens while you were using the Lua, then it will probably stay in a corrupt state. Trying to use the Lua again will most likely result in another panic but shouldn’t result in unsafety.

Implementations§

source§

impl<'lua> Lua<'lua>

source

pub fn new() -> Lua<'lua>

Builds a new empty Lua context.

There are no global variables and the registry is totally empty. Even the functions from the standard library can’t be used.

If you want to use the Lua standard library in the scripts of this context, see the openlibs method

§Example
use hlua::Lua;
let mut lua = Lua::new();
§Panic

The function panics if the underlying call to lua_newstate fails (which indicates lack of memory).

Examples found in repository?
examples/basic.rs (line 7)
6
7
8
9
10
11
12
13
fn main() {
    let mut lua = hlua::Lua::new();

    lua.set("a", 12);
    let val: i32 = lua.execute(r#"return a * 5;"#).unwrap();

    assert_eq!(val, 60);
}
More examples
Hide additional examples
examples/rust_function.rs (line 7)
6
7
8
9
10
11
12
13
fn main() {
    let mut lua = hlua::Lua::new();

    lua.set("foo", hlua::function1(|val: i32| val * 5));

    let val: i32 = lua.execute(r#"return foo(8)"#).unwrap();
    assert_eq!(val, 40);
}
examples/repl.rs (line 9)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    let stdin = stdin();
    loop {
        print!("> ");
        stdout().flush().unwrap();

        let mut line = String::new();
        stdin.read_line(&mut line).unwrap();

        match lua.execute::<AnyLuaValue>(&line) {
            Ok(value) => println!("{:?}", value),
            Err(e) => println!("error: {:?}", e),
        }
    }
}
examples/sound-api.rs (line 5)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    // we create a fill an array named `Sound` which will be used as a class-like interface
    {
        let mut sound_namespace = lua.empty_array("Sound");

        // creating the `Sound.new` function
        sound_namespace.set("new", hlua::function0(|| Sound::new()));
    }

    lua.execute::<()>(r#"
        s = Sound.new();
        s:play();

        print("hello world from within lua!");
        print("is the sound playing:", s:is_playing());

        s:stop();
        print("is the sound playing:", s:is_playing());

    "#)
        .unwrap();
}
source

pub unsafe fn from_existing_state<T>( lua: *mut T, close_at_the_end: bool ) -> Lua<'lua>

Takes an existing lua_State and build a Lua object from it.

If close_at_the_end is true, lua_close will be called on the lua_State in the destructor.

source

pub fn openlibs(&mut self)

Opens all standard Lua libraries.

See the reference for the standard library here: https://www.lua.org/manual/5.2/manual.html#6

This is done by calling luaL_openlibs.

§Example
use hlua::Lua;
let mut lua = Lua::new();
lua.openlibs();
Examples found in repository?
examples/repl.rs (line 10)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    let stdin = stdin();
    loop {
        print!("> ");
        stdout().flush().unwrap();

        let mut line = String::new();
        stdin.read_line(&mut line).unwrap();

        match lua.execute::<AnyLuaValue>(&line) {
            Ok(value) => println!("{:?}", value),
            Err(e) => println!("error: {:?}", e),
        }
    }
}
More examples
Hide additional examples
examples/sound-api.rs (line 6)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    // we create a fill an array named `Sound` which will be used as a class-like interface
    {
        let mut sound_namespace = lua.empty_array("Sound");

        // creating the `Sound.new` function
        sound_namespace.set("new", hlua::function0(|| Sound::new()));
    }

    lua.execute::<()>(r#"
        s = Sound.new();
        s:play();

        print("hello world from within lua!");
        print("is the sound playing:", s:is_playing());

        s:stop();
        print("is the sound playing:", s:is_playing());

    "#)
        .unwrap();
}
source

pub fn open_base(&mut self)

Opens base library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_base

source

pub fn open_bit32(&mut self)

Opens bit32 library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_bit32

source

pub fn open_coroutine(&mut self)

Opens coroutine library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_coroutine

source

pub fn open_debug(&mut self)

Opens debug library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_debug

source

pub fn open_io(&mut self)

Opens io library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_io

source

pub fn open_math(&mut self)

Opens math library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_math

source

pub fn open_os(&mut self)

Opens os library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_os

source

pub fn open_package(&mut self)

Opens package library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_package

source

pub fn open_string(&mut self)

Opens string library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_string

source

pub fn open_table(&mut self)

Opens table library.

https://www.lua.org/manual/5.2/manual.html#pdf-luaopen_table

source

pub fn execute<'a, T>(&'a mut self, code: &str) -> Result<T, LuaError>
where T: for<'g> LuaRead<PushGuard<&'g mut PushGuard<&'a mut Lua<'lua>>>>,

Executes some Lua code in the context.

The code will have access to all the global variables you set with methods such as set. Every time you execute some code in the context, the code can modify these global variables.

The template parameter of this function is the return type of the expression that is being evaluated. In order to avoid compilation error, you should call this function either by doing lua.execute::<T>(...) or let result: T = lua.execute(...); where T is the type of the expression. The function will return an error if the actual return type of the expression doesn’t match the template parameter.

The return type must implement the LuaRead trait. See the documentation at the crate root for more information.

§Examples

Without a return value:

use hlua::Lua;
let mut lua = Lua::new();
lua.execute::<()>("function multiply_by_two(a) return a * 2 end").unwrap();
lua.execute::<()>("twelve = multiply_by_two(6)").unwrap();

With a return value:

use hlua::Lua;
let mut lua = Lua::new();

let twelve: i32 = lua.execute("return 3 * 4;").unwrap();
let sixty = lua.execute::<i32>("return 6 * 10;").unwrap();
Examples found in repository?
examples/basic.rs (line 10)
6
7
8
9
10
11
12
13
fn main() {
    let mut lua = hlua::Lua::new();

    lua.set("a", 12);
    let val: i32 = lua.execute(r#"return a * 5;"#).unwrap();

    assert_eq!(val, 60);
}
More examples
Hide additional examples
examples/rust_function.rs (line 11)
6
7
8
9
10
11
12
13
fn main() {
    let mut lua = hlua::Lua::new();

    lua.set("foo", hlua::function1(|val: i32| val * 5));

    let val: i32 = lua.execute(r#"return foo(8)"#).unwrap();
    assert_eq!(val, 40);
}
examples/repl.rs (line 20)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    let stdin = stdin();
    loop {
        print!("> ");
        stdout().flush().unwrap();

        let mut line = String::new();
        stdin.read_line(&mut line).unwrap();

        match lua.execute::<AnyLuaValue>(&line) {
            Ok(value) => println!("{:?}", value),
            Err(e) => println!("error: {:?}", e),
        }
    }
}
examples/sound-api.rs (lines 16-26)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    // we create a fill an array named `Sound` which will be used as a class-like interface
    {
        let mut sound_namespace = lua.empty_array("Sound");

        // creating the `Sound.new` function
        sound_namespace.set("new", hlua::function0(|| Sound::new()));
    }

    lua.execute::<()>(r#"
        s = Sound.new();
        s:play();

        print("hello world from within lua!");
        print("is the sound playing:", s:is_playing());

        s:stop();
        print("is the sound playing:", s:is_playing());

    "#)
        .unwrap();
}
source

pub fn execute_from_reader<'a, T, R>( &'a mut self, code: R ) -> Result<T, LuaError>
where T: for<'g> LuaRead<PushGuard<&'g mut PushGuard<&'a mut Lua<'lua>>>>, R: Read,

Executes some Lua code on the context.

This does the same thing as the execute method, but the code to execute is loaded from an object that implements Read.

Use this method when you potentially have a large amount of code (for example if you read the code from a file) in order to avoid having to put everything in memory first before passing it to the Lua interpreter.

§Example
use std::fs::File;
use hlua::Lua;

let mut lua = Lua::new();
let script = File::open("script.lua").unwrap();
lua.execute_from_reader::<(), _>(script).unwrap();
source

pub fn get<'l, V, I>(&'l mut self, index: I) -> Option<V>
where I: Borrow<str>, V: LuaRead<PushGuard<&'l mut Lua<'lua>>>,

Reads the value of a global variable.

Returns None if the variable doesn’t exist or has the wrong type.

The type must implement the LuaRead trait. See the documentation at the crate root for more information.

§Example
use hlua::Lua;
let mut lua = Lua::new();
lua.execute::<()>("a = 5").unwrap();
let a: i32 = lua.get("a").unwrap();
assert_eq!(a, 5);
source

pub fn into_get<V, I>(self, index: I) -> Result<V, PushGuard<Self>>
where I: Borrow<str>, V: LuaRead<PushGuard<Lua<'lua>>>,

Reads the value of a global, capturing the context by value.

source

pub fn set<I, V, E>(&mut self, index: I, value: V)
where I: Borrow<str>, for<'a> V: PushOne<&'a mut Lua<'lua>, Err = E>, E: Into<Void>,

Modifies the value of a global variable.

If you want to write an array, you are encouraged to use the empty_array method instead.

The type must implement the PushOne trait. See the documentation at the crate root for more information.

§Example
use hlua::Lua;
let mut lua = Lua::new();

lua.set("a", 12);
let six: i32 = lua.execute("return a / 2;").unwrap();
assert_eq!(six, 6);
Examples found in repository?
examples/basic.rs (line 9)
6
7
8
9
10
11
12
13
fn main() {
    let mut lua = hlua::Lua::new();

    lua.set("a", 12);
    let val: i32 = lua.execute(r#"return a * 5;"#).unwrap();

    assert_eq!(val, 60);
}
More examples
Hide additional examples
examples/rust_function.rs (line 9)
6
7
8
9
10
11
12
13
fn main() {
    let mut lua = hlua::Lua::new();

    lua.set("foo", hlua::function1(|val: i32| val * 5));

    let val: i32 = lua.execute(r#"return foo(8)"#).unwrap();
    assert_eq!(val, 40);
}
source

pub fn checked_set<I, V, E>(&mut self, index: I, value: V) -> Result<(), E>
where I: Borrow<str>, for<'a> V: PushOne<&'a mut Lua<'lua>, Err = E>,

Modifies the value of a global variable.

source

pub fn empty_array<'a, I>( &'a mut self, index: I ) -> LuaTable<PushGuard<&'a mut Lua<'lua>>>
where I: Borrow<str>,

Sets the value of a global variable to an empty array, then loads it.

This is the function you should use if you want to set the value of a global variable to an array. After calling it, you will obtain a LuaTable object which you can then fill with the elements of the array.

§Example
use hlua::Lua;
let mut lua = Lua::new();
lua.openlibs();     // Necessary for `ipairs`.

{
    let mut array = lua.empty_array("my_values");
    array.set(1, 10);       // Don't forget that Lua arrays are indexed from 1.
    array.set(2, 15);
    array.set(3, 20);
}

let sum: i32 = lua.execute(r#"
    local sum = 0
    for i, val in ipairs(my_values) do
        sum = sum + val
    end
    return sum
"#).unwrap();

assert_eq!(sum, 45);
Examples found in repository?
examples/sound-api.rs (line 10)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    // we create a fill an array named `Sound` which will be used as a class-like interface
    {
        let mut sound_namespace = lua.empty_array("Sound");

        // creating the `Sound.new` function
        sound_namespace.set("new", hlua::function0(|| Sound::new()));
    }

    lua.execute::<()>(r#"
        s = Sound.new();
        s:play();

        print("hello world from within lua!");
        print("is the sound playing:", s:is_playing());

        s:stop();
        print("is the sound playing:", s:is_playing());

    "#)
        .unwrap();
}
source

pub fn globals_table<'a>(&'a mut self) -> LuaTable<PushGuard<&'a mut Lua<'lua>>>

Loads the array containing the global variables.

In lua, the global variables accessible from the lua code are all part of a table which you can load here.

§Examples

The function can be used to write global variables, just like set.

use hlua::Lua;
let mut lua = Lua::new();
lua.globals_table().set("a", 5);
assert_eq!(lua.get::<i32, _>("a"), Some(5));

A more useful feature for this function is that it allows you to set the metatable of the global variables. See TODO for more info.

use hlua::Lua;
use hlua::AnyLuaValue;

let mut lua = Lua::new();
{
    let mut metatable = lua.globals_table().get_or_create_metatable();
    metatable.set("__index", hlua::function2(|_: AnyLuaValue, var: String| -> AnyLuaValue {
        println!("The user tried to access the variable {:?}", var);
        AnyLuaValue::LuaNumber(48.0)
    }));
}

let b: i32 = lua.execute("return b * 2;").unwrap();
// -> The user tried to access the variable "b"

assert_eq!(b, 96);

Trait Implementations§

source§

impl<'a, 'lua> AsLua<'lua> for Lua<'lua>

source§

impl<'lua> AsMutLua<'lua> for Lua<'lua>

source§

fn as_mut_lua(&mut self) -> LuaContext

Returns the raw Lua context.
source§

impl<'lua> Debug for Lua<'lua>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'lua> Drop for Lua<'lua>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'lua> Freeze for Lua<'lua>

§

impl<'lua> RefUnwindSafe for Lua<'lua>

§

impl<'lua> Send for Lua<'lua>

§

impl<'lua> !Sync for Lua<'lua>

§

impl<'lua> Unpin for Lua<'lua>

§

impl<'lua> UnwindSafe for Lua<'lua>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.