mlua/examples/examples.rs

171 lines
5.4 KiB
Rust
Raw Normal View History

2017-05-21 20:47:32 -05:00
extern crate rlua;
use std::f32;
use rlua::{Lua, Result, Function, Variadic, UserData, UserDataMethods, MetaMethod};
2017-05-21 20:47:32 -05:00
fn examples() -> Result<()> {
// Create a Lua context with Lua::new(). Eventually, this will allow
// further control on the lua std library, and will specifically allow
// limiting Lua to a subset of "safe" functionality.
2017-05-21 20:47:32 -05:00
let lua = Lua::new();
// You can get and set global variables. Notice that the globals table here
2017-06-25 21:25:28 -05:00
// is a permanent reference to _G, and it is mutated behind the scenes as
// lua code is loaded. This API is based heavily around internal mutation
// (just like lua itself).
Another major API change, out of stack space is not an Err It, ahem "should not" be possible to exhaust lua stack space in normal usage, and causing stack errors to be Err is slightly obnoxious. I have been wanting to make this change for a while, and removing the callback API from tables makes this sensible *I think*. I can think of a couple of ways that this is not technically true, but I think that they are acceptable, or should be handled differently. One, you can make arbitrarily sized LuaVariadic values. I think this is maybe a bug already, because there is an argument limit in Lua which is lower than the stack limit. I'm not sure what happens there, but if it is a stack based panic, (or any panic?) it is a bug. Two, I believe that if you recurse over and over between lua -> rust -> lua -> rust etc, and call rlua API functions, you might get a stack panic. I think for trusted lua code, this is morally equivalent to a regular stack overflow in plain rust, which is already.. well it's not a panic but it's some kind of safe crash I'm not sure, so I think this is acceptable. For *untrusted* lua code, this could theoretically be a problem if the API provided a callback that would call back into lua, then some lua script could force a stack based panic. There are so many concerns with untrusted lua code, and this library is NOT safe enough yet for untrusted code (it doesn't even provide an option to limit lua to the safe API subset yet!), so this is not currently an issue. When the library provides support for "safe lua", it should come with big warnings anyway, and being able to force a stack panic is pretty minor in comparison. I think if there are other ways to cause unbounded stack usage, that it is a bug, or there can be an error just for that situation, like argument count limits. This commit also fixes several stupid bugs with tests, stack checking, and panics.
2017-06-25 15:52:32 -05:00
let globals = lua.globals();
2017-05-21 20:47:32 -05:00
globals.set("string_var", "hello")?;
globals.set("int_var", 42)?;
2017-05-21 20:47:32 -05:00
assert_eq!(globals.get::<_, String>("string_var")?, "hello");
assert_eq!(globals.get::<_, i64>("int_var")?, 42);
2017-05-21 20:47:32 -05:00
// You can load and evaluate lua code. The second parameter here gives the
// chunk a better name when lua error messages are printed.
2017-05-21 20:47:32 -05:00
lua.exec::<()>(
r#"
2017-05-21 20:47:32 -05:00
global = 'foo'..'bar'
"#,
Some("example code"),
)?;
assert_eq!(globals.get::<_, String>("global")?, "foobar");
2017-05-21 20:47:32 -05:00
assert_eq!(lua.eval::<i32>("1 + 1", None)?, 2);
assert_eq!(lua.eval::<bool>("false == false", None)?, true);
assert_eq!(lua.eval::<i32>("return 1 + 2", None)?, 3);
2017-05-21 20:47:32 -05:00
// You can create and manage lua tables
Another major API change, out of stack space is not an Err It, ahem "should not" be possible to exhaust lua stack space in normal usage, and causing stack errors to be Err is slightly obnoxious. I have been wanting to make this change for a while, and removing the callback API from tables makes this sensible *I think*. I can think of a couple of ways that this is not technically true, but I think that they are acceptable, or should be handled differently. One, you can make arbitrarily sized LuaVariadic values. I think this is maybe a bug already, because there is an argument limit in Lua which is lower than the stack limit. I'm not sure what happens there, but if it is a stack based panic, (or any panic?) it is a bug. Two, I believe that if you recurse over and over between lua -> rust -> lua -> rust etc, and call rlua API functions, you might get a stack panic. I think for trusted lua code, this is morally equivalent to a regular stack overflow in plain rust, which is already.. well it's not a panic but it's some kind of safe crash I'm not sure, so I think this is acceptable. For *untrusted* lua code, this could theoretically be a problem if the API provided a callback that would call back into lua, then some lua script could force a stack based panic. There are so many concerns with untrusted lua code, and this library is NOT safe enough yet for untrusted code (it doesn't even provide an option to limit lua to the safe API subset yet!), so this is not currently an issue. When the library provides support for "safe lua", it should come with big warnings anyway, and being able to force a stack panic is pretty minor in comparison. I think if there are other ways to cause unbounded stack usage, that it is a bug, or there can be an error just for that situation, like argument count limits. This commit also fixes several stupid bugs with tests, stack checking, and panics.
2017-06-25 15:52:32 -05:00
let array_table = lua.create_table();
2017-05-21 20:47:32 -05:00
array_table.set(1, "one")?;
array_table.set(2, "two")?;
array_table.set(3, "three")?;
assert_eq!(array_table.len()?, 3);
2017-05-21 20:47:32 -05:00
Another major API change, out of stack space is not an Err It, ahem "should not" be possible to exhaust lua stack space in normal usage, and causing stack errors to be Err is slightly obnoxious. I have been wanting to make this change for a while, and removing the callback API from tables makes this sensible *I think*. I can think of a couple of ways that this is not technically true, but I think that they are acceptable, or should be handled differently. One, you can make arbitrarily sized LuaVariadic values. I think this is maybe a bug already, because there is an argument limit in Lua which is lower than the stack limit. I'm not sure what happens there, but if it is a stack based panic, (or any panic?) it is a bug. Two, I believe that if you recurse over and over between lua -> rust -> lua -> rust etc, and call rlua API functions, you might get a stack panic. I think for trusted lua code, this is morally equivalent to a regular stack overflow in plain rust, which is already.. well it's not a panic but it's some kind of safe crash I'm not sure, so I think this is acceptable. For *untrusted* lua code, this could theoretically be a problem if the API provided a callback that would call back into lua, then some lua script could force a stack based panic. There are so many concerns with untrusted lua code, and this library is NOT safe enough yet for untrusted code (it doesn't even provide an option to limit lua to the safe API subset yet!), so this is not currently an issue. When the library provides support for "safe lua", it should come with big warnings anyway, and being able to force a stack panic is pretty minor in comparison. I think if there are other ways to cause unbounded stack usage, that it is a bug, or there can be an error just for that situation, like argument count limits. This commit also fixes several stupid bugs with tests, stack checking, and panics.
2017-06-25 15:52:32 -05:00
let map_table = lua.create_table();
2017-05-21 20:47:32 -05:00
map_table.set("one", 1)?;
map_table.set("two", 2)?;
map_table.set("three", 3)?;
let v: i64 = map_table.get("two")?;
assert_eq!(v, 2);
// You can pass values like Table back into Lua
2017-05-21 20:47:32 -05:00
globals.set("array_table", array_table)?;
globals.set("map_table", map_table)?;
2017-05-21 20:47:32 -05:00
lua.eval::<()>(
r#"
2017-05-21 20:47:32 -05:00
for k, v in pairs(array_table) do
print(k, v)
end
for k, v in pairs(map_table) do
print(k, v)
end
"#,
None,
)?;
2017-05-21 20:47:32 -05:00
// You can load lua functions
let print: Function = globals.get("print")?;
2017-05-21 20:47:32 -05:00
print.call::<_, ()>("hello from rust")?;
2017-06-25 21:25:28 -05:00
// This API handles variadics using Heterogeneous Lists. This is one way to
// call a function with multiple parameters:
2017-05-21 20:47:32 -05:00
print.call::<_, ()>(("hello", "again", "from", "rust"))?;
2017-05-21 20:47:32 -05:00
// You can bind rust functions to lua as well
let check_equal = lua.create_function(|lua, args| {
// Functions wrapped in lua receive their arguments packed together as
// MultiValue. The first thing that most wrapped functions will do
// is "unpack" this MultiValue into its parts. Due to lifetime type
// signature limitations, this cannot be done automatically from the
// function signature, but this will be fixed with ATCs. Notice the use
// of the hlist macros again.
let (list1, list2) = lua.unpack::<(Vec<String>, Vec<String>)>(args)?;
2017-05-21 20:47:32 -05:00
// This function just checks whether two string lists are equal, and in
// an inefficient way. Results are returned with lua.pack, which takes
// any number of values and turns them back into MultiValue. In this
// way, multiple values can also be returned to Lua. Again, this cannot
// be inferred as part of the function signature due to the same
// lifetime type signature limitations.
2017-05-21 20:47:32 -05:00
lua.pack(list1 == list2)
Another major API change, out of stack space is not an Err It, ahem "should not" be possible to exhaust lua stack space in normal usage, and causing stack errors to be Err is slightly obnoxious. I have been wanting to make this change for a while, and removing the callback API from tables makes this sensible *I think*. I can think of a couple of ways that this is not technically true, but I think that they are acceptable, or should be handled differently. One, you can make arbitrarily sized LuaVariadic values. I think this is maybe a bug already, because there is an argument limit in Lua which is lower than the stack limit. I'm not sure what happens there, but if it is a stack based panic, (or any panic?) it is a bug. Two, I believe that if you recurse over and over between lua -> rust -> lua -> rust etc, and call rlua API functions, you might get a stack panic. I think for trusted lua code, this is morally equivalent to a regular stack overflow in plain rust, which is already.. well it's not a panic but it's some kind of safe crash I'm not sure, so I think this is acceptable. For *untrusted* lua code, this could theoretically be a problem if the API provided a callback that would call back into lua, then some lua script could force a stack based panic. There are so many concerns with untrusted lua code, and this library is NOT safe enough yet for untrusted code (it doesn't even provide an option to limit lua to the safe API subset yet!), so this is not currently an issue. When the library provides support for "safe lua", it should come with big warnings anyway, and being able to force a stack panic is pretty minor in comparison. I think if there are other ways to cause unbounded stack usage, that it is a bug, or there can be an error just for that situation, like argument count limits. This commit also fixes several stupid bugs with tests, stack checking, and panics.
2017-06-25 15:52:32 -05:00
});
globals.set("check_equal", check_equal)?;
2017-05-21 20:47:32 -05:00
2017-06-25 21:25:28 -05:00
// You can also accept variadic arguments to rust callbacks.
2017-05-21 20:57:15 -05:00
let join = lua.create_function(|lua, args| {
let strings = lua.unpack::<Variadic<String>>(args)?.0;
2017-06-15 09:26:39 -05:00
// (This is quadratic!, it's just an example!)
lua.pack(strings.iter().fold("".to_owned(), |a, b| a + b))
Another major API change, out of stack space is not an Err It, ahem "should not" be possible to exhaust lua stack space in normal usage, and causing stack errors to be Err is slightly obnoxious. I have been wanting to make this change for a while, and removing the callback API from tables makes this sensible *I think*. I can think of a couple of ways that this is not technically true, but I think that they are acceptable, or should be handled differently. One, you can make arbitrarily sized LuaVariadic values. I think this is maybe a bug already, because there is an argument limit in Lua which is lower than the stack limit. I'm not sure what happens there, but if it is a stack based panic, (or any panic?) it is a bug. Two, I believe that if you recurse over and over between lua -> rust -> lua -> rust etc, and call rlua API functions, you might get a stack panic. I think for trusted lua code, this is morally equivalent to a regular stack overflow in plain rust, which is already.. well it's not a panic but it's some kind of safe crash I'm not sure, so I think this is acceptable. For *untrusted* lua code, this could theoretically be a problem if the API provided a callback that would call back into lua, then some lua script could force a stack based panic. There are so many concerns with untrusted lua code, and this library is NOT safe enough yet for untrusted code (it doesn't even provide an option to limit lua to the safe API subset yet!), so this is not currently an issue. When the library provides support for "safe lua", it should come with big warnings anyway, and being able to force a stack panic is pretty minor in comparison. I think if there are other ways to cause unbounded stack usage, that it is a bug, or there can be an error just for that situation, like argument count limits. This commit also fixes several stupid bugs with tests, stack checking, and panics.
2017-06-25 15:52:32 -05:00
});
globals.set("join", join)?;
2017-05-21 20:57:15 -05:00
2017-06-15 09:26:39 -05:00
assert_eq!(
lua.eval::<bool>(
r#"check_equal({"a", "b", "c"}, {"a", "b", "c"})"#,
None,
2017-06-15 09:26:39 -05:00
)?,
true
);
assert_eq!(
lua.eval::<bool>(
r#"check_equal({"a", "b", "c"}, {"d", "e", "f"})"#,
None,
2017-06-15 09:26:39 -05:00
)?,
false
);
assert_eq!(lua.eval::<String>(r#"join("a", "b", "c")"#, None)?, "abc");
2017-05-21 20:47:32 -05:00
// You can create userdata with methods and metamethods defined on them.
2017-06-25 21:25:28 -05:00
// Here's a worked example that shows many of the features of this API
// together
2017-05-21 20:47:32 -05:00
#[derive(Copy, Clone)]
struct Vec2(f32, f32);
impl UserData for Vec2 {
fn add_methods(methods: &mut UserDataMethods<Self>) {
methods.add_method("magnitude", |lua, vec, _: ()| {
2017-05-21 20:47:32 -05:00
let mag_squared = vec.0 * vec.0 + vec.1 * vec.1;
lua.pack(mag_squared.sqrt())
});
methods.add_meta_function(MetaMethod::Add, |lua, params| {
let (vec1, vec2) = lua.unpack::<(Vec2, Vec2)>(params)?;
2017-05-21 20:47:32 -05:00
lua.pack(Vec2(vec1.0 + vec2.0, vec1.1 + vec2.1))
});
}
}
let vec2_constructor = lua.create_function(|lua, args| {
let (x, y) = lua.unpack::<(f32, f32)>(args)?;
lua.pack(Vec2(x, y))
Another major API change, out of stack space is not an Err It, ahem "should not" be possible to exhaust lua stack space in normal usage, and causing stack errors to be Err is slightly obnoxious. I have been wanting to make this change for a while, and removing the callback API from tables makes this sensible *I think*. I can think of a couple of ways that this is not technically true, but I think that they are acceptable, or should be handled differently. One, you can make arbitrarily sized LuaVariadic values. I think this is maybe a bug already, because there is an argument limit in Lua which is lower than the stack limit. I'm not sure what happens there, but if it is a stack based panic, (or any panic?) it is a bug. Two, I believe that if you recurse over and over between lua -> rust -> lua -> rust etc, and call rlua API functions, you might get a stack panic. I think for trusted lua code, this is morally equivalent to a regular stack overflow in plain rust, which is already.. well it's not a panic but it's some kind of safe crash I'm not sure, so I think this is acceptable. For *untrusted* lua code, this could theoretically be a problem if the API provided a callback that would call back into lua, then some lua script could force a stack based panic. There are so many concerns with untrusted lua code, and this library is NOT safe enough yet for untrusted code (it doesn't even provide an option to limit lua to the safe API subset yet!), so this is not currently an issue. When the library provides support for "safe lua", it should come with big warnings anyway, and being able to force a stack panic is pretty minor in comparison. I think if there are other ways to cause unbounded stack usage, that it is a bug, or there can be an error just for that situation, like argument count limits. This commit also fixes several stupid bugs with tests, stack checking, and panics.
2017-06-25 15:52:32 -05:00
});
globals.set("vec2", vec2_constructor)?;
2017-05-21 20:47:32 -05:00
assert!(
lua.eval::<f32>(
"(vec2(1, 2) + vec2(2, 2)):magnitude()",
None,
)? - 5.0 < f32::EPSILON
);
2017-05-21 20:47:32 -05:00
Ok(())
}
fn main() {
examples().unwrap();
}