-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
58 lines (48 loc) · 1.48 KB
/
main.rs
File metadata and controls
58 lines (48 loc) · 1.48 KB
1
2
3
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use luars::{Lua, LuaResult, LuaUserData, SafeOption, Stdlib, lua_methods};
#[derive(LuaUserData)]
struct Counter {
pub count: i64,
}
#[lua_methods]
impl Counter {
pub fn new(count: i64) -> Self {
Self { count }
}
pub fn inc(&mut self, delta: i64) {
self.count += delta;
}
pub fn get(&self) -> i64 {
self.count
}
}
fn main() -> LuaResult<()> {
let mut lua = Lua::new(SafeOption::default());
lua.load_stdlibs(Stdlib::All)?;
lua.register_function("slugify", |name: String| {
name.trim().to_lowercase().replace(' ', "-")
})?;
lua.register_type::<Counter>("Counter")?;
let config = lua.create_table_from([("host", "localhost"), ("mode", "demo")])?;
lua.globals().set("config", config)?;
let (slug, host, count): (String, String, i64) = lua.scope(|scope| {
let prefix = String::from("user:");
let format_name = scope
.create_function_with(&prefix, |prefix: &String, value: String| {
format!("{prefix}{value}")
})?;
scope.globals().set("format_name", &format_name)?;
scope
.load(
r#"
local counter = Counter.new(1)
counter:inc(41)
return format_name(slugify("Hello Lua")), config.host, counter:get()
"#,
)
.eval_multi()
})?;
println!("slug: {slug}");
println!("host: {host}");
println!("count: {count}");
Ok(())
}