pub struct Lua { /* private fields */ }Expand description
What runs scripts: a RemedyLua state with its globals, heap and limits. One thread
uses it at a time; it may move between threads (Send).
Implementations§
Source§impl Lua
impl Lua
Sourcepub fn new(limits: Limits, libs: Libs) -> Lua
pub fn new(limits: Limits, libs: Libs) -> Lua
A state with limits, offering libs.
Examples found in repository?
More examples
8fn main() {
9 let a: Vec<String> = std::env::args().collect();
10 let src = a.get(1).cloned().unwrap_or_default();
11 let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14 let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15 lua.set_print(|_| {});
16 let h0 = hwm();
17 let t = std::time::Instant::now();
18 let r = lua.exec(src, "=s");
19 let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20 let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21 println!(
22 "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23 hwm() >> 10,
24 h0 >> 10,
25 mem >> 20,
26 now >> 20,
27 lua.memory_used() >> 20,
28 t.elapsed(),
29 fuel - lua.fuel_left(),
30 &r[..r.len().min(200)]
31 );
32}10fn main() {
11 let a: Vec<String> = std::env::args().collect();
12 let setup = a.get(1).cloned().unwrap_or_default();
13 let body = a.get(2).cloned().unwrap_or_default();
14 let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17 let mut worst = Duration::ZERO;
18 let mut last = String::new();
19 for _ in 0..5 {
20 let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21 lua.set_print(|_| {});
22 lua.exec(&setup, "=setup").unwrap();
23 let t0 = Instant::now();
24 let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25 lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26 let f = lua.load(&body, "=body").unwrap();
27 let start = Instant::now();
28 let r = lua.call(f.value(), &[]);
29 let el = start.elapsed();
30 worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31 last = format!("{:?}", r.err());
32 }
33 println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}16fn main() {
17 let mut args = std::env::args().skip(1);
18 let file = args.next().unwrap();
19 let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20 let mode = args.next().unwrap_or_else(|| "host".into());
21 let src = std::fs::read(&file).unwrap();
22 let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23 let before = hwm();
24 let t = std::time::Instant::now();
25 let outcome = match mode.as_str() {
26 "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27 "call" => {
28 let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29 let s = lua.create_string(&src).unwrap();
30 lua.set_global("src", s).unwrap();
31 let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32 format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33 }
34 _ => {
35 let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36 format!("{:?}", lua.load(&src, name).map(|_| ()))
37 }
38 };
39 let peak = hwm();
40 println!(
41 "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42 t.elapsed(),
43 peak as f64 / 1e6,
44 before as f64 / 1e6,
45 limit as f64 / 1048576.0,
46 peak as f64 / limit as f64
47 );
48}11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}37fn main() {
38 let mb: usize = std::env::args().nth(1).and_then(|a| a.parse().ok()).unwrap_or(4);
39 let src = match std::env::var("FRONTBENCH_FILE") {
40 Ok(f) => std::fs::read_to_string(f).unwrap(),
41 Err(_) => source(mb << 20),
42 };
43 // `FRONTBENCH_DUMP=path`: writes the source there (for `examples/frontmem.rs`) and stops.
44 if let Ok(path) = std::env::var("FRONTBENCH_DUMP") {
45 std::fs::write(path, &src).unwrap();
46 return;
47 }
48 let runs = 5;
49 let mut parse = f64::MAX;
50 let mut load = f64::MAX;
51 for _ in 0..runs {
52 let t = Instant::now();
53 let d = remedy_lua::check(src.as_bytes(), "bench.lua");
54 assert!(d.is_empty(), "{d:?}");
55 parse = parse.min(t.elapsed().as_secs_f64());
56 let mut lua = Lua::new(Limits::unmetered(), Libs::STANDARD);
57 let t = Instant::now();
58 lua.load(&src, "=bench").unwrap();
59 load = load.min(t.elapsed().as_secs_f64());
60 }
61 let mbs = src.len() as f64 / (1 << 20) as f64;
62 // With the oracle built in, the recursive front end side by side, alternating run by
63 // run so both see the same machine load.
64 #[cfg(feature = "front-oracle")]
65 {
66 let mut best = [[f64::MAX; 3]; 2];
67 for _ in 0..runs * 3 {
68 for (side, old) in best.iter_mut().zip([true, false]) {
69 let t = remedy_lua::__front::time(src.as_bytes(), "bench.lua", old).unwrap();
70 for (b, t) in side.iter_mut().zip(t) {
71 *b = b.min(t.as_secs_f64() * 1e3);
72 }
73 }
74 }
75 for (label, b) in ["old (recursive)", "new (iterative)"].iter().zip(best) {
76 println!("{label}: parse {:6.1} ms compile {:6.1} ms drop {:5.1} ms", b[0], b[1], b[2]);
77 }
78 }
79 println!("source: {:.2} MB, {} lines (best of {runs})", mbs, src.lines().count());
80 println!("parse: {:8.1} ms {:6.1} MB/s", parse * 1e3, mbs / parse);
81 println!("parse + compile: {:8.1} ms {:6.1} MB/s", load * 1e3, mbs / load);
82}Sourcepub fn load(
&mut self,
source: impl AsRef<[u8]>,
name: &str,
) -> Result<Root, Error>
pub fn load( &mut self, source: impl AsRef<[u8]>, name: &str, ) -> Result<Root, Error>
Compiles source as a chunk named name (=name prints as name in messages,
@file as a file name); the dialect follows the name’s extension. The chunk is a
function: call it to run it.
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}More examples
10fn main() {
11 let a: Vec<String> = std::env::args().collect();
12 let setup = a.get(1).cloned().unwrap_or_default();
13 let body = a.get(2).cloned().unwrap_or_default();
14 let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17 let mut worst = Duration::ZERO;
18 let mut last = String::new();
19 for _ in 0..5 {
20 let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21 lua.set_print(|_| {});
22 lua.exec(&setup, "=setup").unwrap();
23 let t0 = Instant::now();
24 let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25 lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26 let f = lua.load(&body, "=body").unwrap();
27 let start = Instant::now();
28 let r = lua.call(f.value(), &[]);
29 let el = start.elapsed();
30 worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31 last = format!("{:?}", r.err());
32 }
33 println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}16fn main() {
17 let mut args = std::env::args().skip(1);
18 let file = args.next().unwrap();
19 let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20 let mode = args.next().unwrap_or_else(|| "host".into());
21 let src = std::fs::read(&file).unwrap();
22 let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23 let before = hwm();
24 let t = std::time::Instant::now();
25 let outcome = match mode.as_str() {
26 "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27 "call" => {
28 let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29 let s = lua.create_string(&src).unwrap();
30 lua.set_global("src", s).unwrap();
31 let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32 format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33 }
34 _ => {
35 let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36 format!("{:?}", lua.load(&src, name).map(|_| ()))
37 }
38 };
39 let peak = hwm();
40 println!(
41 "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42 t.elapsed(),
43 peak as f64 / 1e6,
44 before as f64 / 1e6,
45 limit as f64 / 1048576.0,
46 peak as f64 / limit as f64
47 );
48}37fn main() {
38 let mb: usize = std::env::args().nth(1).and_then(|a| a.parse().ok()).unwrap_or(4);
39 let src = match std::env::var("FRONTBENCH_FILE") {
40 Ok(f) => std::fs::read_to_string(f).unwrap(),
41 Err(_) => source(mb << 20),
42 };
43 // `FRONTBENCH_DUMP=path`: writes the source there (for `examples/frontmem.rs`) and stops.
44 if let Ok(path) = std::env::var("FRONTBENCH_DUMP") {
45 std::fs::write(path, &src).unwrap();
46 return;
47 }
48 let runs = 5;
49 let mut parse = f64::MAX;
50 let mut load = f64::MAX;
51 for _ in 0..runs {
52 let t = Instant::now();
53 let d = remedy_lua::check(src.as_bytes(), "bench.lua");
54 assert!(d.is_empty(), "{d:?}");
55 parse = parse.min(t.elapsed().as_secs_f64());
56 let mut lua = Lua::new(Limits::unmetered(), Libs::STANDARD);
57 let t = Instant::now();
58 lua.load(&src, "=bench").unwrap();
59 load = load.min(t.elapsed().as_secs_f64());
60 }
61 let mbs = src.len() as f64 / (1 << 20) as f64;
62 // With the oracle built in, the recursive front end side by side, alternating run by
63 // run so both see the same machine load.
64 #[cfg(feature = "front-oracle")]
65 {
66 let mut best = [[f64::MAX; 3]; 2];
67 for _ in 0..runs * 3 {
68 for (side, old) in best.iter_mut().zip([true, false]) {
69 let t = remedy_lua::__front::time(src.as_bytes(), "bench.lua", old).unwrap();
70 for (b, t) in side.iter_mut().zip(t) {
71 *b = b.min(t.as_secs_f64() * 1e3);
72 }
73 }
74 }
75 for (label, b) in ["old (recursive)", "new (iterative)"].iter().zip(best) {
76 println!("{label}: parse {:6.1} ms compile {:6.1} ms drop {:5.1} ms", b[0], b[1], b[2]);
77 }
78 }
79 println!("source: {:.2} MB, {} lines (best of {runs})", mbs, src.lines().count());
80 println!("parse: {:8.1} ms {:6.1} MB/s", parse * 1e3, mbs / parse);
81 println!("parse + compile: {:8.1} ms {:6.1} MB/s", load * 1e3, mbs / load);
82}23fn main() {
24 let mut args = std::env::args().skip(1);
25 let cases: Vec<String> = match args.next() {
26 Some(c) if c != "all" => vec![c],
27 _ => ["do", "dots", "flat", "locals", "keys", "strs"].iter().map(|s| (*s).to_owned()).collect(),
28 };
29 let points: u32 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24);
30 // A third argument: interrupt only there (milliseconds into the load).
31 let only: Option<u64> = args.next().and_then(|a| a.parse().ok());
32 for case in cases {
33 let src = source(&case);
34 let full = {
35 let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
36 let t = Instant::now();
37 let r = lua.load(&src, "=t").map(|_| ());
38 let e = t.elapsed();
39 assert!(r.is_ok(), "{case}: {r:?}");
40 e
41 };
42 let mut worst = (Duration::ZERO, Duration::ZERO);
43 for k in 1..=points {
44 let at = only.map_or(full * k / (points + 1), Duration::from_millis);
45 let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
46 let h = lua.interrupt_handle();
47 let t = std::thread::spawn(move || {
48 std::thread::sleep(at);
49 h.interrupt();
50 Instant::now()
51 });
52 let started = Instant::now();
53 let r = lua.load(&src, "=t").map(|_| ());
54 let end = Instant::now();
55 let fired = t.join().unwrap();
56 if r.is_err() {
57 let late = end.saturating_duration_since(fired);
58 if std::env::var("FRONTSTOP_VERBOSE").is_ok() {
59 println!(" at {at:?}: {late:?} late, {:?} into the load", fired.saturating_duration_since(started));
60 }
61 if late > worst.0 {
62 worst = (late, at);
63 }
64 }
65 lua.interrupt_handle().reset();
66 let _ = lua.load("return 1", "=ok");
67 }
68 println!("{case:8} {:.1} MB, load {full:?}: worst {:?} late (interrupted at {:?})", src.len() as f64 / 1e6, worst.0, worst.1);
69 }
70}155fn main() {
156 let fuel: u64 = std::env::var("FUELCAL_FUEL").ok().and_then(|s| s.parse().ok()).unwrap_or(3_000_000);
157 let only = std::env::var("FUELCAL_ONLY").ok();
158 let md = std::env::var_os("FUELCAL_MD").is_some();
159 let mut rows: Vec<(&str, f64, String)> = Vec::new();
160 for &(name, setup, body) in CASES {
161 if only.as_deref().is_some_and(|o| !name.contains(o)) {
162 continue;
163 }
164 let src = format!("{setup}\nwhile true do\n{body}\nend");
165 let mut best = f64::MAX;
166 let mut note = String::new();
167 for _ in 0..3 {
168 let mut lua = Lua::new(Limits::default().fuel(fuel).memory(256 << 20).hash_seed(7), Libs::ALL);
169 let f = match lua.load(&src, "=cal") {
170 Ok(f) => f,
171 Err(e) => {
172 note = format!("load: {e:?}");
173 break;
174 }
175 };
176 let t = std::time::Instant::now();
177 let r = lua.call(f.value(), &[]);
178 let el = t.elapsed().as_secs_f64();
179 let used = fuel - lua.fuel_left();
180 match r {
181 Err(Error::Limit(LimitKind::Fuel)) => {}
182 other => note = format!("{other:?}").chars().take(80).collect(),
183 }
184 best = best.min(el * 1e9 / used.max(1) as f64);
185 }
186 if !md {
187 println!("{best:9.1} ns/unit {name} {note}");
188 }
189 rows.push((name, best, note));
190 }
191 let mut v: Vec<f64> = rows.iter().map(|r| r.1).collect();
192 v.sort_by(f64::total_cmp);
193 let median = v.get(v.len() / 2).copied().unwrap_or(0.0);
194 if md {
195 println!("| case | ns/unit | x median |\n|---|---:|---:|");
196 for (name, ns, note) in &rows {
197 println!("| {name}{} | {ns:.1} | {:.2} |", if note.is_empty() { String::new() } else { format!(" ({note})") }, ns / median);
198 }
199 }
200 println!("median {median:.1} ns/unit, max {:.1} ({:.1}x)", v.last().copied().unwrap_or(0.0), v.last().copied().unwrap_or(0.0) / median);
201 let mut worst: Vec<_> = rows.iter().filter(|r| r.1 > 4.0 * median).collect();
202 worst.sort_by(|a, b| b.1.total_cmp(&a.1));
203 for (name, ns, _) in worst {
204 println!(" over 4x: {name} {ns:.1} ({:.1}x)", ns / median);
205 }
206}Sourcepub fn load_with(
&mut self,
source: impl AsRef<[u8]>,
name: &str,
dialect: Dialect,
) -> Result<Root, Error>
pub fn load_with( &mut self, source: impl AsRef<[u8]>, name: &str, dialect: Dialect, ) -> Result<Root, Error>
Lua::load in a given dialect.
Sourcepub fn exec(
&mut self,
source: impl AsRef<[u8]>,
name: &str,
) -> Result<Vec<Value>, Error>
pub fn exec( &mut self, source: impl AsRef<[u8]>, name: &str, ) -> Result<Vec<Value>, Error>
Compiles and runs source: what it returns.
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}More examples
8fn main() {
9 let a: Vec<String> = std::env::args().collect();
10 let src = a.get(1).cloned().unwrap_or_default();
11 let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14 let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15 lua.set_print(|_| {});
16 let h0 = hwm();
17 let t = std::time::Instant::now();
18 let r = lua.exec(src, "=s");
19 let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20 let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21 println!(
22 "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23 hwm() >> 10,
24 h0 >> 10,
25 mem >> 20,
26 now >> 20,
27 lua.memory_used() >> 20,
28 t.elapsed(),
29 fuel - lua.fuel_left(),
30 &r[..r.len().min(200)]
31 );
32}10fn main() {
11 let a: Vec<String> = std::env::args().collect();
12 let setup = a.get(1).cloned().unwrap_or_default();
13 let body = a.get(2).cloned().unwrap_or_default();
14 let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17 let mut worst = Duration::ZERO;
18 let mut last = String::new();
19 for _ in 0..5 {
20 let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21 lua.set_print(|_| {});
22 lua.exec(&setup, "=setup").unwrap();
23 let t0 = Instant::now();
24 let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25 lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26 let f = lua.load(&body, "=body").unwrap();
27 let start = Instant::now();
28 let r = lua.call(f.value(), &[]);
29 let el = start.elapsed();
30 worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31 last = format!("{:?}", r.err());
32 }
33 println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}16fn main() {
17 let mut args = std::env::args().skip(1);
18 let file = args.next().unwrap();
19 let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20 let mode = args.next().unwrap_or_else(|| "host".into());
21 let src = std::fs::read(&file).unwrap();
22 let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23 let before = hwm();
24 let t = std::time::Instant::now();
25 let outcome = match mode.as_str() {
26 "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27 "call" => {
28 let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29 let s = lua.create_string(&src).unwrap();
30 lua.set_global("src", s).unwrap();
31 let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32 format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33 }
34 _ => {
35 let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36 format!("{:?}", lua.load(&src, name).map(|_| ()))
37 }
38 };
39 let peak = hwm();
40 println!(
41 "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42 t.elapsed(),
43 peak as f64 / 1e6,
44 before as f64 / 1e6,
45 limit as f64 / 1048576.0,
46 peak as f64 / limit as f64
47 );
48}11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn call(&mut self, f: Value, args: &[Value]) -> Result<Vec<Value>, Error>
pub fn call(&mut self, f: Value, args: &[Value]) -> Result<Vec<Value>, Error>
Calls f with args (a function, or a value with __call): its results. Fuel and
the time limit start afresh for a call from the host (not for one made inside a host
function). From the host, the results stay valid until its next call returns, and
the values it made before this call are released when it returns; inside a host
function, until that function’s next call (see the crate docs). Root a
value to keep it longer.
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}More examples
10fn main() {
11 let a: Vec<String> = std::env::args().collect();
12 let setup = a.get(1).cloned().unwrap_or_default();
13 let body = a.get(2).cloned().unwrap_or_default();
14 let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17 let mut worst = Duration::ZERO;
18 let mut last = String::new();
19 for _ in 0..5 {
20 let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21 lua.set_print(|_| {});
22 lua.exec(&setup, "=setup").unwrap();
23 let t0 = Instant::now();
24 let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25 lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26 let f = lua.load(&body, "=body").unwrap();
27 let start = Instant::now();
28 let r = lua.call(f.value(), &[]);
29 let el = start.elapsed();
30 worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31 last = format!("{:?}", r.err());
32 }
33 println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}155fn main() {
156 let fuel: u64 = std::env::var("FUELCAL_FUEL").ok().and_then(|s| s.parse().ok()).unwrap_or(3_000_000);
157 let only = std::env::var("FUELCAL_ONLY").ok();
158 let md = std::env::var_os("FUELCAL_MD").is_some();
159 let mut rows: Vec<(&str, f64, String)> = Vec::new();
160 for &(name, setup, body) in CASES {
161 if only.as_deref().is_some_and(|o| !name.contains(o)) {
162 continue;
163 }
164 let src = format!("{setup}\nwhile true do\n{body}\nend");
165 let mut best = f64::MAX;
166 let mut note = String::new();
167 for _ in 0..3 {
168 let mut lua = Lua::new(Limits::default().fuel(fuel).memory(256 << 20).hash_seed(7), Libs::ALL);
169 let f = match lua.load(&src, "=cal") {
170 Ok(f) => f,
171 Err(e) => {
172 note = format!("load: {e:?}");
173 break;
174 }
175 };
176 let t = std::time::Instant::now();
177 let r = lua.call(f.value(), &[]);
178 let el = t.elapsed().as_secs_f64();
179 let used = fuel - lua.fuel_left();
180 match r {
181 Err(Error::Limit(LimitKind::Fuel)) => {}
182 other => note = format!("{other:?}").chars().take(80).collect(),
183 }
184 best = best.min(el * 1e9 / used.max(1) as f64);
185 }
186 if !md {
187 println!("{best:9.1} ns/unit {name} {note}");
188 }
189 rows.push((name, best, note));
190 }
191 let mut v: Vec<f64> = rows.iter().map(|r| r.1).collect();
192 v.sort_by(f64::total_cmp);
193 let median = v.get(v.len() / 2).copied().unwrap_or(0.0);
194 if md {
195 println!("| case | ns/unit | x median |\n|---|---:|---:|");
196 for (name, ns, note) in &rows {
197 println!("| {name}{} | {ns:.1} | {:.2} |", if note.is_empty() { String::new() } else { format!(" ({note})") }, ns / median);
198 }
199 }
200 println!("median {median:.1} ns/unit, max {:.1} ({:.1}x)", v.last().copied().unwrap_or(0.0), v.last().copied().unwrap_or(0.0) / median);
201 let mut worst: Vec<_> = rows.iter().filter(|r| r.1 > 4.0 * median).collect();
202 worst.sort_by(|a, b| b.1.total_cmp(&a.1));
203 for (name, ns, _) in worst {
204 println!(" over 4x: {name} {ns:.1} ({:.1}x)", ns / median);
205 }
206}32fn main() {
33 let a: Vec<String> = std::env::args().collect();
34 let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35 let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36 let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37 // The table grows first (its array part's growth is not the interner's).
38 lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39 let (clock, st) = gap_clock();
40 lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41 let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42 let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43 st.lock().unwrap().0 = Instant::now();
44 let t = Instant::now();
45 lua.call(f.value(), &[]).unwrap();
46 let all = t.elapsed();
47 let g = *st.lock().unwrap();
48 println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49 println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50 let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51 println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52 println!(
53 "{:?}",
54 lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55 );
56 if k == 0 {
57 return;
58 }
59 // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60 // a load stops after it, at points along the load.
61 let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62 let full = {
63 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64 let t = Instant::now();
65 l.load(&src, "=t").unwrap();
66 t.elapsed()
67 };
68 let mut worst = Duration::ZERO;
69 for p in 1..=12u32 {
70 let at = full * p / 13;
71 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72 let h = l.interrupt_handle();
73 let th = std::thread::spawn(move || {
74 std::thread::sleep(at);
75 h.interrupt();
76 Instant::now()
77 });
78 let r = l.load(&src, "=t").map(|_| ());
79 let end = Instant::now();
80 let fired = th.join().unwrap();
81 if r.is_err() {
82 worst = worst.max(end.saturating_duration_since(fired));
83 }
84 }
85 println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}Sourcepub fn collector_status(&self) -> CollectorStatus
pub fn collector_status(&self) -> CollectorStatus
Where the collector stands, and the fuel it is known to need (SEC8-F3 O5): for a host that gives calls a fixed fuel, to tell a call that will be spent in the collector from one that will run the script (at the memory limit an allocation’s emergency collection can take hundreds of such calls: SEC8-G3, a known limitation). Two different quantities:
owed_fuel: work already done and not yet charged. The collector’s next steps (or next collection) charge it before they do more. Exact.remaining_fuel_at_least: a floor on the fuel the cycle under way still needs past that. Not an estimate of the cost: marking finds the objects it must mark as it goes, so while it runs (more_may_be_found) the rest is not known ahead. A full collection (collectgarbage(),collect_garbage, or the one an allocation makes at the memory limit) finishes the cycle under way and then runs a whole new one, which neither figure includes. Reading it enters nothing and charges nothing.
Sourcepub fn call_global(
&mut self,
name: &str,
args: &[Value],
) -> Result<Option<Vec<Value>>, Error>
pub fn call_global( &mut self, name: &str, args: &[Value], ) -> Result<Option<Vec<Value>>, Error>
Calls the global function name (or a dotted path, table.field, read raw), if
there is one: Ok(None) when it is missing or not a function.
Examples found in repository?
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn get_global(&mut self, name: &str) -> Result<Value, Error>
pub fn get_global(&mut self, name: &str) -> Result<Value, Error>
A global, read raw (no metamethods run). A read: it does not enter the state, so it
neither finishes an atomic phase a call before stopped in nor pays for one (made
with create_string, the name entered, and while that phase did not fit in the
call’s fuel the read failed with Limit(Fuel): SEC8-F3). The name is looked up, not
made: table keys are interned, so a name never made is no global’s. (A value read
here and stored from the host is checked then, the phase finished first: SEC7-H2.)
Sourcepub fn set_global(&mut self, name: &str, v: Value) -> Result<(), Error>
pub fn set_global(&mut self, name: &str, v: Value) -> Result<(), Error>
Sets a global, raw.
Examples found in repository?
16fn main() {
17 let mut args = std::env::args().skip(1);
18 let file = args.next().unwrap();
19 let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20 let mode = args.next().unwrap_or_else(|| "host".into());
21 let src = std::fs::read(&file).unwrap();
22 let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23 let before = hwm();
24 let t = std::time::Instant::now();
25 let outcome = match mode.as_str() {
26 "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27 "call" => {
28 let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29 let s = lua.create_string(&src).unwrap();
30 lua.set_global("src", s).unwrap();
31 let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32 format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33 }
34 _ => {
35 let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36 format!("{:?}", lua.load(&src, name).map(|_| ()))
37 }
38 };
39 let peak = hwm();
40 println!(
41 "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42 t.elapsed(),
43 peak as f64 / 1e6,
44 before as f64 / 1e6,
45 limit as f64 / 1048576.0,
46 peak as f64 / limit as f64
47 );
48}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn table_get(&self, t: TableRef, k: Value) -> Value
pub fn table_get(&self, t: TableRef, k: Value) -> Value
t[k], raw (nil for a handle whose table was collected).
Sourcepub fn table_set(
&mut self,
t: TableRef,
k: Value,
v: Value,
) -> Result<(), Error>
pub fn table_set( &mut self, t: TableRef, k: Value, v: Value, ) -> Result<(), Error>
t[k] = v, raw.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}Sourcepub fn get(&mut self, t: Value, k: Value) -> Result<Value, Error>
pub fn get(&mut self, t: Value, k: Value) -> Result<Value, Error>
t[k] with metamethods (which run under the call’s fuel).
Sourcepub fn set(&mut self, t: Value, k: Value, v: Value) -> Result<(), Error>
pub fn set(&mut self, t: Value, k: Value, v: Value) -> Result<(), Error>
t[k] = v with metamethods.
Sourcepub fn table_len(&self, t: TableRef) -> i64
pub fn table_len(&self, t: TableRef) -> i64
#t, raw (0 for a handle whose table was collected).
Sourcepub fn table_pairs(&self, t: TableRef) -> Vec<(Value, Value)>
pub fn table_pairs(&self, t: TableRef) -> Vec<(Value, Value)>
Every entry of t, raw, in traversal order (none for a stale handle).
Sourcepub fn create_table(&mut self) -> Result<TableRef, Error>
pub fn create_table(&mut self) -> Result<TableRef, Error>
A new empty table.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn create_string(&mut self, s: impl AsRef<[u8]>) -> Result<Value, Error>
pub fn create_string(&mut self, s: impl AsRef<[u8]>) -> Result<Value, Error>
A string.
Examples found in repository?
16fn main() {
17 let mut args = std::env::args().skip(1);
18 let file = args.next().unwrap();
19 let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20 let mode = args.next().unwrap_or_else(|| "host".into());
21 let src = std::fs::read(&file).unwrap();
22 let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23 let before = hwm();
24 let t = std::time::Instant::now();
25 let outcome = match mode.as_str() {
26 "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27 "call" => {
28 let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29 let s = lua.create_string(&src).unwrap();
30 lua.set_global("src", s).unwrap();
31 let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32 format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33 }
34 _ => {
35 let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36 format!("{:?}", lua.load(&src, name).map(|_| ()))
37 }
38 };
39 let peak = hwm();
40 println!(
41 "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42 t.elapsed(),
43 peak as f64 / 1e6,
44 before as f64 / 1e6,
45 limit as f64 / 1048576.0,
46 peak as f64 / limit as f64
47 );
48}Sourcepub fn raw_equal(&self, a: &Value, b: &Value) -> bool
pub fn raw_equal(&self, a: &Value, b: &Value) -> bool
Raw equality as Lua’s rawequal sees it: strings by content (two equal long
strings made apart are different objects, so Value’s == tells them apart),
1 == 1.0, other objects by identity. No metamethods run.
Sourcepub fn to_string_lossy(&self, v: Value) -> Option<String>
pub fn to_string_lossy(&self, v: Value) -> Option<String>
A string value as text (invalid UTF-8 replaced).
Examples found in repository?
8fn main() {
9 let a: Vec<String> = std::env::args().collect();
10 let src = a.get(1).cloned().unwrap_or_default();
11 let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14 let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15 lua.set_print(|_| {});
16 let h0 = hwm();
17 let t = std::time::Instant::now();
18 let r = lua.exec(src, "=s");
19 let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20 let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21 println!(
22 "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23 hwm() >> 10,
24 h0 >> 10,
25 mem >> 20,
26 now >> 20,
27 lua.memory_used() >> 20,
28 t.elapsed(),
29 fuel - lua.fuel_left(),
30 &r[..r.len().min(200)]
31 );
32}More examples
16fn main() {
17 let mut args = std::env::args().skip(1);
18 let file = args.next().unwrap();
19 let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20 let mode = args.next().unwrap_or_else(|| "host".into());
21 let src = std::fs::read(&file).unwrap();
22 let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23 let before = hwm();
24 let t = std::time::Instant::now();
25 let outcome = match mode.as_str() {
26 "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27 "call" => {
28 let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29 let s = lua.create_string(&src).unwrap();
30 lua.set_global("src", s).unwrap();
31 let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32 format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33 }
34 _ => {
35 let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36 format!("{:?}", lua.load(&src, name).map(|_| ()))
37 }
38 };
39 let peak = hwm();
40 println!(
41 "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42 t.elapsed(),
43 peak as f64 / 1e6,
44 before as f64 / 1e6,
45 limit as f64 / 1048576.0,
46 peak as f64 / limit as f64
47 );
48}Sourcepub fn set_metatable(
&mut self,
t: TableRef,
meta: Option<TableRef>,
) -> Result<(), Error>
pub fn set_metatable( &mut self, t: TableRef, meta: Option<TableRef>, ) -> Result<(), Error>
Sets a table’s metatable.
Sourcepub fn root(&mut self, v: Value) -> Root
pub fn root(&mut self, v: Value) -> Root
Keeps v alive while the returned handle lives.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn create_function(
&mut self,
name: &str,
f: impl Fn(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + Sync + 'static,
) -> Result<Value, Error>
pub fn create_function( &mut self, name: &str, f: impl Fn(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + Sync + 'static, ) -> Result<Value, Error>
A Rust function scripts can call. It gets the arguments and returns the results,
or an error the script sees as an error (catchable by pcall unless it is an
Error::Limit; an Error::Runtime that a lua.call inside it returned passes
the script’s own error value on). It may call back into the state (lua.call), and
a script may reach it again while it runs, so it is Fn + Sync: keep mutable state
behind a Mutex or in Lua::app_data_mut, or use Lua::create_function_mut,
which takes an FnMut that need not be Sync and refuses to run inside itself. When it returns, the host’s interrupt and the
call’s deadline are checked, so time spent waiting in it counts. A panic in it
unwinds to the host and poisons the state; catch panics inside it to contain them.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn register(
&mut self,
name: &str,
f: impl Fn(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + Sync + 'static,
) -> Result<(), Error>
pub fn register( &mut self, name: &str, f: impl Fn(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + Sync + 'static, ) -> Result<(), Error>
Makes a Rust function a global (name) or a field of a global table (lib.name,
the table made if missing).
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn register_mut(
&mut self,
name: &str,
f: impl FnMut(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + 'static,
) -> Result<(), Error>
pub fn register_mut( &mut self, name: &str, f: impl FnMut(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + 'static, ) -> Result<(), Error>
Lua::register for a Lua::create_function_mut function.
Sourcepub fn create_function_mut(
&mut self,
name: &str,
f: impl FnMut(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + 'static,
) -> Result<Value, Error>
pub fn create_function_mut( &mut self, name: &str, f: impl FnMut(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + 'static, ) -> Result<Value, Error>
A Rust function scripts can call, like Lua::create_function, that may keep
mutable state and need not be Sync. Because it is FnMut, it cannot run inside
itself: when a script reaches it again while it runs (through a callback it calls),
that inner call is an ordinary script error, “a host function was called again while
it ran”. create_function needs Sync because it may run inside itself, and the
state, which is Send, shares it between those runs; Mutex makes this one Sync
without that.
Sourcepub fn create_userdata<T: Any + Send>(
&mut self,
data: T,
meta: Option<TableRef>,
) -> Result<Value, Error>
pub fn create_userdata<T: Any + Send>( &mut self, data: T, meta: Option<TableRef>, ) -> Result<Value, Error>
A full userdata holding data, with an optional metatable (for methods: set its
__index; a __gc field never runs). It counts size_of::<T>() plus a small
header against the memory limit; declare what T owns on the heap (a Vec’s
buffer) with Lua::set_userdata_size.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn set_userdata_size(&mut self, v: Value, bytes: usize) -> Result<(), Error>
pub fn set_userdata_size(&mut self, v: Value, bytes: usize) -> Result<(), Error>
Sets what the userdata v counts against the memory limit, besides a small header:
bytes, in place of size_of::<T>(). A host whose userdata owns heap memory (a
buffer a script asked for) declares it here, size_of::<T>() + buffer.capacity(),
when it grows or shrinks; the difference is charged now, so a script cannot make
the host allocate past its budget. Over the limit (or past isize::MAX, the largest
allocation there is): Error::Limit(Memory) and nothing changes (inside a host
function, return the error, so the call stops).
Sourcepub fn create_userdata_tracked<T: Any + Send>(
&mut self,
data: T,
meta: Option<TableRef>,
key: u64,
) -> Result<Value, Error>
pub fn create_userdata_tracked<T: Any + Send>( &mut self, data: T, meta: Option<TableRef>, key: u64, ) -> Result<Value, Error>
A userdata like Lua::create_userdata whose collection the host hears about: once
no script or root can reach it and the collector frees it, key is queued for
Lua::take_collected. For host objects that must be released when scripts drop
their handles; no Lua code runs at collection (there is no __gc). It counts 8 bytes
more than an untracked one: the room its key takes in that queue.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}Sourcepub fn userdata<T: Any>(&self, v: Value) -> Option<&T>
pub fn userdata<T: Any>(&self, v: Value) -> Option<&T>
The data of a userdata, if it holds a T.
Sourcepub fn userdata_mut<T: Any>(&mut self, v: Value) -> Option<&mut T>
pub fn userdata_mut<T: Any>(&mut self, v: Value) -> Option<&mut T>
The data of a userdata, mutably, if it holds a T.
Sourcepub fn to_data(&self, v: Value, limits: DataLimits) -> Result<Data, Error>
pub fn to_data(&self, v: Value, limits: DataLimits) -> Result<Data, Error>
Copies a value out as owned Data, raw (no metamethod runs: __pairs and
__index are ignored), within limits. A function, userdata or thread, or a table
nested deeper than limits.depth (a table that holds itself, say), is an
Error::Host.
Sourcepub fn from_data(&mut self, d: &Data) -> Result<Value, Error>
pub fn from_data(&mut self, d: &Data) -> Result<Value, Error>
Makes a value from owned Data (nil and NaN keys are skipped), nested at most 64
deep; its size is bounded by the memory limit only. Lua::from_data_with bounds it.
Examples found in repository?
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn from_data_with(
&mut self,
d: &Data,
limits: DataLimits,
) -> Result<Value, Error>
pub fn from_data_with( &mut self, d: &Data, limits: DataLimits, ) -> Result<Value, Error>
Lua::from_data within limits, checked before anything is made: deeper (than
limits.depth, and never more than 64), more values or more string bytes is an
Error::Host, as for Lua::to_data.
Sourcepub fn set_warnings(&mut self, on: bool)
pub fn set_warnings(&mut self, on: bool)
Turns warn output on or off, as a script’s warn("@on") / warn("@off") does.
Warnings start off, as in C Lua’s luaL_newstate; they go where print goes, and
only with the PRINT library allowed. A script can still switch them afterwards.
Sourcepub fn memory_used(&self) -> usize
pub fn memory_used(&self) -> usize
Bytes the state’s objects hold now, free slots included (they are resident: a slab keeps the slots below its last object).
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}More examples
8fn main() {
9 let a: Vec<String> = std::env::args().collect();
10 let src = a.get(1).cloned().unwrap_or_default();
11 let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14 let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15 lua.set_print(|_| {});
16 let h0 = hwm();
17 let t = std::time::Instant::now();
18 let r = lua.exec(src, "=s");
19 let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20 let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21 println!(
22 "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23 hwm() >> 10,
24 h0 >> 10,
25 mem >> 20,
26 now >> 20,
27 lua.memory_used() >> 20,
28 t.elapsed(),
29 fuel - lua.fuel_left(),
30 &r[..r.len().min(200)]
31 );
32}11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn limits(&self) -> Limits
pub fn limits(&self) -> Limits
The limits.
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}Sourcepub fn set_limits(&mut self, limits: Limits)
pub fn set_limits(&mut self, limits: Limits)
Changes the limits (the memory cap applies to what is allocated from now on). The
dialect and seed are the state’s for life: strict_5_4 and hash_seed keep the
values the state was made with (the math table and __le must agree, and the
hashing has already used the seed), whatever limits says.
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}Sourcepub fn fuel_left(&self) -> u64
pub fn fuel_left(&self) -> u64
Fuel left in the current (or last) call.
Examples found in repository?
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29 let r0 = rss();
30 let mut lua = state(mem, fast);
31 lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32 lua.set_limits(lua.limits().fuel(fuel));
33 let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34 let t = Instant::now();
35 let r = lua.call(f.value(), &[]);
36 let el = t.elapsed().as_nanos() as f64;
37 let used = fuel - lua.fuel_left();
38 let mu = lua.memory_used();
39 let g = rss().saturating_sub(r0);
40 (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}More examples
8fn main() {
9 let a: Vec<String> = std::env::args().collect();
10 let src = a.get(1).cloned().unwrap_or_default();
11 let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14 let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15 lua.set_print(|_| {});
16 let h0 = hwm();
17 let t = std::time::Instant::now();
18 let r = lua.exec(src, "=s");
19 let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20 let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21 println!(
22 "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23 hwm() >> 10,
24 h0 >> 10,
25 mem >> 20,
26 now >> 20,
27 lua.memory_used() >> 20,
28 t.elapsed(),
29 fuel - lua.fuel_left(),
30 &r[..r.len().min(200)]
31 );
32}155fn main() {
156 let fuel: u64 = std::env::var("FUELCAL_FUEL").ok().and_then(|s| s.parse().ok()).unwrap_or(3_000_000);
157 let only = std::env::var("FUELCAL_ONLY").ok();
158 let md = std::env::var_os("FUELCAL_MD").is_some();
159 let mut rows: Vec<(&str, f64, String)> = Vec::new();
160 for &(name, setup, body) in CASES {
161 if only.as_deref().is_some_and(|o| !name.contains(o)) {
162 continue;
163 }
164 let src = format!("{setup}\nwhile true do\n{body}\nend");
165 let mut best = f64::MAX;
166 let mut note = String::new();
167 for _ in 0..3 {
168 let mut lua = Lua::new(Limits::default().fuel(fuel).memory(256 << 20).hash_seed(7), Libs::ALL);
169 let f = match lua.load(&src, "=cal") {
170 Ok(f) => f,
171 Err(e) => {
172 note = format!("load: {e:?}");
173 break;
174 }
175 };
176 let t = std::time::Instant::now();
177 let r = lua.call(f.value(), &[]);
178 let el = t.elapsed().as_secs_f64();
179 let used = fuel - lua.fuel_left();
180 match r {
181 Err(Error::Limit(LimitKind::Fuel)) => {}
182 other => note = format!("{other:?}").chars().take(80).collect(),
183 }
184 best = best.min(el * 1e9 / used.max(1) as f64);
185 }
186 if !md {
187 println!("{best:9.1} ns/unit {name} {note}");
188 }
189 rows.push((name, best, note));
190 }
191 let mut v: Vec<f64> = rows.iter().map(|r| r.1).collect();
192 v.sort_by(f64::total_cmp);
193 let median = v.get(v.len() / 2).copied().unwrap_or(0.0);
194 if md {
195 println!("| case | ns/unit | x median |\n|---|---:|---:|");
196 for (name, ns, note) in &rows {
197 println!("| {name}{} | {ns:.1} | {:.2} |", if note.is_empty() { String::new() } else { format!(" ({note})") }, ns / median);
198 }
199 }
200 println!("median {median:.1} ns/unit, max {:.1} ({:.1}x)", v.last().copied().unwrap_or(0.0), v.last().copied().unwrap_or(0.0) / median);
201 let mut worst: Vec<_> = rows.iter().filter(|r| r.1 > 4.0 * median).collect();
202 worst.sort_by(|a, b| b.1.total_cmp(&a.1));
203 for (name, ns, _) in worst {
204 println!(" over 4x: {name} {ns:.1} ({:.1}x)", ns / median);
205 }
206}Sourcepub fn interrupt_handle(&self) -> Interrupt
pub fn interrupt_handle(&self) -> Interrupt
The state’s interrupt: a handle to keep (on any thread) and set to stop the running call. Every handle from the same state is the same interrupt.
Examples found in repository?
23fn main() {
24 let mut args = std::env::args().skip(1);
25 let cases: Vec<String> = match args.next() {
26 Some(c) if c != "all" => vec![c],
27 _ => ["do", "dots", "flat", "locals", "keys", "strs"].iter().map(|s| (*s).to_owned()).collect(),
28 };
29 let points: u32 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24);
30 // A third argument: interrupt only there (milliseconds into the load).
31 let only: Option<u64> = args.next().and_then(|a| a.parse().ok());
32 for case in cases {
33 let src = source(&case);
34 let full = {
35 let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
36 let t = Instant::now();
37 let r = lua.load(&src, "=t").map(|_| ());
38 let e = t.elapsed();
39 assert!(r.is_ok(), "{case}: {r:?}");
40 e
41 };
42 let mut worst = (Duration::ZERO, Duration::ZERO);
43 for k in 1..=points {
44 let at = only.map_or(full * k / (points + 1), Duration::from_millis);
45 let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
46 let h = lua.interrupt_handle();
47 let t = std::thread::spawn(move || {
48 std::thread::sleep(at);
49 h.interrupt();
50 Instant::now()
51 });
52 let started = Instant::now();
53 let r = lua.load(&src, "=t").map(|_| ());
54 let end = Instant::now();
55 let fired = t.join().unwrap();
56 if r.is_err() {
57 let late = end.saturating_duration_since(fired);
58 if std::env::var("FRONTSTOP_VERBOSE").is_ok() {
59 println!(" at {at:?}: {late:?} late, {:?} into the load", fired.saturating_duration_since(started));
60 }
61 if late > worst.0 {
62 worst = (late, at);
63 }
64 }
65 lua.interrupt_handle().reset();
66 let _ = lua.load("return 1", "=ok");
67 }
68 println!("{case:8} {:.1} MB, load {full:?}: worst {:?} late (interrupted at {:?})", src.len() as f64 / 1e6, worst.0, worst.1);
69 }
70}More examples
32fn main() {
33 let a: Vec<String> = std::env::args().collect();
34 let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35 let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36 let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37 // The table grows first (its array part's growth is not the interner's).
38 lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39 let (clock, st) = gap_clock();
40 lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41 let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42 let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43 st.lock().unwrap().0 = Instant::now();
44 let t = Instant::now();
45 lua.call(f.value(), &[]).unwrap();
46 let all = t.elapsed();
47 let g = *st.lock().unwrap();
48 println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49 println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50 let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51 println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52 println!(
53 "{:?}",
54 lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55 );
56 if k == 0 {
57 return;
58 }
59 // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60 // a load stops after it, at points along the load.
61 let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62 let full = {
63 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64 let t = Instant::now();
65 l.load(&src, "=t").unwrap();
66 t.elapsed()
67 };
68 let mut worst = Duration::ZERO;
69 for p in 1..=12u32 {
70 let at = full * p / 13;
71 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72 let h = l.interrupt_handle();
73 let th = std::thread::spawn(move || {
74 std::thread::sleep(at);
75 h.interrupt();
76 Instant::now()
77 });
78 let r = l.load(&src, "=t").map(|_| ());
79 let end = Instant::now();
80 let fired = th.join().unwrap();
81 if r.is_err() {
82 worst = worst.max(end.saturating_duration_since(fired));
83 }
84 }
85 println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}Sourcepub fn set_time_limit(&mut self, limit: Option<(Clock, Duration)>)
pub fn set_time_limit(&mut self, limit: Option<(Clock, Duration)>)
Stops each call from the host once it has run limit by clock (looked at every few
thousand steps, so the stop comes within a fraction of a millisecond of work past it):
Error::Limit(LimitKind::Time). None removes the time limit.
Examples found in repository?
10fn main() {
11 let a: Vec<String> = std::env::args().collect();
12 let setup = a.get(1).cloned().unwrap_or_default();
13 let body = a.get(2).cloned().unwrap_or_default();
14 let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17 let mut worst = Duration::ZERO;
18 let mut last = String::new();
19 for _ in 0..5 {
20 let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21 lua.set_print(|_| {});
22 lua.exec(&setup, "=setup").unwrap();
23 let t0 = Instant::now();
24 let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25 lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26 let f = lua.load(&body, "=body").unwrap();
27 let start = Instant::now();
28 let r = lua.call(f.value(), &[]);
29 let el = start.elapsed();
30 worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31 last = format!("{:?}", r.err());
32 }
33 println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}More examples
32fn main() {
33 let a: Vec<String> = std::env::args().collect();
34 let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35 let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36 let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37 // The table grows first (its array part's growth is not the interner's).
38 lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39 let (clock, st) = gap_clock();
40 lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41 let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42 let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43 st.lock().unwrap().0 = Instant::now();
44 let t = Instant::now();
45 lua.call(f.value(), &[]).unwrap();
46 let all = t.elapsed();
47 let g = *st.lock().unwrap();
48 println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49 println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50 let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51 println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52 println!(
53 "{:?}",
54 lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55 );
56 if k == 0 {
57 return;
58 }
59 // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60 // a load stops after it, at points along the load.
61 let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62 let full = {
63 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64 let t = Instant::now();
65 l.load(&src, "=t").unwrap();
66 t.elapsed()
67 };
68 let mut worst = Duration::ZERO;
69 for p in 1..=12u32 {
70 let at = full * p / 13;
71 let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72 let h = l.interrupt_handle();
73 let th = std::thread::spawn(move || {
74 std::thread::sleep(at);
75 h.interrupt();
76 Instant::now()
77 });
78 let r = l.load(&src, "=t").map(|_| ());
79 let end = Instant::now();
80 let fired = th.join().unwrap();
81 if r.is_err() {
82 worst = worst.max(end.saturating_duration_since(fired));
83 }
84 }
85 println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}Sourcepub fn set_app_data<T: Any + Send>(&mut self, data: T)
pub fn set_app_data<T: Any + Send>(&mut self, data: T)
Keeps data with the state: the host’s own data for its functions to reach
(Lua::app_data_mut), one value per type, replacing the last of that type. Send
because the state is Send (it may move to another thread with what it holds).
Sourcepub fn app_data_mut<T: Any>(&mut self) -> Option<&mut T>
pub fn app_data_mut<T: Any>(&mut self) -> Option<&mut T>
The host’s data of type T, mutably, if set.
Sourcepub fn take_app_data<T: Any>(&mut self) -> Option<T>
pub fn take_app_data<T: Any>(&mut self) -> Option<T>
Takes the host’s data of type T out of the state.
Sourcepub fn take_collected(&mut self) -> Vec<u64>
pub fn take_collected(&mut self) -> Vec<u64>
The keys of tracked userdata (Lua::create_userdata_tracked) the collector has
freed since the last take, oldest first. Nothing runs in Lua when one is collected:
the host drains this queue when it chooses (after a call, or a collection). Each key
waiting here counts 8 bytes against the memory limit (charged when its userdata was
made) until it is taken, so a host that tracks userdata drains it after each call.
Sourcepub fn collect_garbage(&mut self) -> Result<(), Error>
pub fn collect_garbage(&mut self) -> Result<(), Error>
Runs a complete collection now. From the host (not inside a host function) it also lets go of the values held for the host since its last call (see the crate docs): root what must survive it.
Examples found in repository?
11fn main() {
12 let a: Vec<String> = std::env::args().collect();
13 let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14 let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15 let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16 lua.exec("KEEP = {}", "=s").unwrap();
17 let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18 let mut roots = Vec::new();
19 lua.collect_garbage().unwrap();
20 let (r0, m0) = (rss(), lua.memory_used());
21 for i in 0..n {
22 let v = match kind.as_str() {
23 "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24 "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25 "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26 "root" => Value::Int(i as i64),
27 "register" => {
28 lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29 Value::Nil
30 }
31 _ => panic!("kind"),
32 };
33 if kind.ends_with("root") {
34 let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35 roots.push(lua.root(t));
36 if kind == "root" {
37 continue;
38 }
39 }
40 if !v.is_nil() {
41 lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42 }
43 if i % 4096 == 0 {
44 lua.exec("", "=s").unwrap();
45 }
46 }
47 lua.exec("", "=s").unwrap();
48 lua.collect_garbage().unwrap();
49 let (r1, m1) = (rss(), lua.memory_used());
50 let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51 println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52 drop(roots);
53}More examples
14fn main() {
15 let a: Vec<String> = std::env::args().collect();
16 let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17 let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18 // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19 let collect = a.get(3).is_none_or(|s| s != "nocollect");
20 let token = Arc::new(());
21 let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22 let meta = lua.create_table().unwrap();
23 let meta = lua.root(Value::Table(meta));
24 let Value::Table(mt) = meta.value() else { unreachable!() };
25 lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26 let mut prev: Vec<(&'static str, usize)> = Vec::new();
27 for i in 0..n {
28 let t = Arc::clone(&token);
29 let f = lua.create_function("echo", move |_, a| {
30 let _held = &t;
31 Ok(a.to_vec())
32 }).unwrap();
33 let rf = lua.root(f);
34 let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35 let ru = lua.root(ud);
36 let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37 assert_eq!(r, vec![Value::Bool(true)]);
38 let t2 = Arc::clone(&token);
39 lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40 let _held = &t2;
41 Ok(vec![Value::Int(1)])
42 }).unwrap();
43 let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44 lua.set_global("last", d).unwrap();
45 drop((rf, ru));
46 if collect && i % 200 == 0 {
47 lua.collect_garbage().unwrap();
48 }
49 if i % step == 0 {
50 let sizes = lua.internal_sizes();
51 let changed: Vec<String> = sizes
52 .iter()
53 .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54 .map(|(k, v)| format!("{k}={v}"))
55 .collect();
56 println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57 prev = sizes;
58 }
59 }
60}Sourcepub fn take_output(&mut self) -> String
pub fn take_output(&mut self) -> String
Takes what print (and warn) wrote since the last take; empty when a sink is set.
Each call from the host may write at most Limits::output bytes; more is dropped.
Sourcepub fn set_print(&mut self, sink: impl FnMut(&str) + Send + 'static)
pub fn set_print(&mut self, sink: impl FnMut(&str) + Send + 'static)
Sends print (and warn) output to sink instead of the buffer, within
Limits::output per call. The sink runs inside the call: a panic in it poisons
the state.
Examples found in repository?
More examples
8fn main() {
9 let a: Vec<String> = std::env::args().collect();
10 let src = a.get(1).cloned().unwrap_or_default();
11 let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12 let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14 let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15 lua.set_print(|_| {});
16 let h0 = hwm();
17 let t = std::time::Instant::now();
18 let r = lua.exec(src, "=s");
19 let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20 let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21 println!(
22 "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23 hwm() >> 10,
24 h0 >> 10,
25 mem >> 20,
26 now >> 20,
27 lua.memory_used() >> 20,
28 t.elapsed(),
29 fuel - lua.fuel_left(),
30 &r[..r.len().min(200)]
31 );
32}10fn main() {
11 let a: Vec<String> = std::env::args().collect();
12 let setup = a.get(1).cloned().unwrap_or_default();
13 let body = a.get(2).cloned().unwrap_or_default();
14 let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15 let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16 let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17 let mut worst = Duration::ZERO;
18 let mut last = String::new();
19 for _ in 0..5 {
20 let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21 lua.set_print(|_| {});
22 lua.exec(&setup, "=setup").unwrap();
23 let t0 = Instant::now();
24 let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25 lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26 let f = lua.load(&body, "=body").unwrap();
27 let start = Instant::now();
28 let r = lua.call(f.value(), &[]);
29 let el = start.elapsed();
30 worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31 last = format!("{:?}", r.err());
32 }
33 println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}Sourcepub fn clear_print(&mut self)
pub fn clear_print(&mut self)
Drops the sink Lua::set_print set: output goes to the buffer again
(Lua::take_output).
Sourcepub fn set_os_clocks(&mut self, wall: Option<Clock>, cpu: Option<Clock>)
pub fn set_os_clocks(&mut self, wall: Option<Clock>, cpu: Option<Clock>)
Sets the clocks of the os library: wall, the time since the Unix epoch, for
os.time and os.date; cpu, the time the program has run, for os.clock. By
default they are the system’s (the process clock from when the state was made), and
in a browser (wasm32-unknown-unknown, which has no clock in std) there are none.
None makes that clock read as 0, which also makes a replay independent of the time.
Sourcepub fn set_env(&mut self, name: impl AsRef<[u8]>, value: Option<&[u8]>)
pub fn set_env(&mut self, name: impl AsRef<[u8]>, value: Option<&[u8]>)
Sets what os.getenv(name) returns (Libs::ENV): Some(value) adds or replaces
name, None removes it. The map starts empty, and nothing else reaches it: the
process environment is never read. Neither copy counts against the memory limit; the
string os.getenv makes does.
Sourcepub fn set_stdin(&mut self, stream: Option<Box<dyn Stream>>)
pub fn set_stdin(&mut self, stream: Option<Box<dyn Stream>>)
Sets io.stdin (Libs::IO): what io.read and io.lines() read by default. None
is the default, an empty stream.
Sourcepub fn set_stdout(&mut self, stream: Option<Box<dyn Stream>>)
pub fn set_stdout(&mut self, stream: Option<Box<dyn Stream>>)
Sets io.stdout (Libs::IO): where io.write writes by default. None is the
default: where print writes (the host’s sink or Lua::take_output).
Sourcepub fn set_stderr(&mut self, stream: Option<Box<dyn Stream>>)
pub fn set_stderr(&mut self, stream: Option<Box<dyn Stream>>)
Sets io.stderr (Libs::IO). None is the default: where print writes.
Sourcepub fn set_file_opener(
&mut self,
opener: Option<impl Fn(&str, &str) -> Result<Box<dyn Stream>, IoError> + Send + Sync + 'static>,
)
pub fn set_file_opener( &mut self, opener: Option<impl Fn(&str, &str) -> Result<Box<dyn Stream>, IoError> + Send + Sync + 'static>, )
Sets what io.open(name, mode) (and io.lines(name), io.input(name),
io.output(name)) asks for a file (Libs::IO): the name (up to its first zero
byte; one that is not UTF-8 is never asked for) and a mode io.open accepted (C’s
[rwa]%+?b*). An error is the script’s nil, "name: message", code. None
(the default) has every name fail with “No such file or directory”.
Sourcepub fn clear_env(&mut self)
pub fn clear_env(&mut self)
Empties os.getenv’s map (Lua::set_env).
Sourcepub fn set_utc_offset(&mut self, seconds: i64)
pub fn set_utc_offset(&mut self, seconds: i64)
Sets the time zone os.date uses for local time, in seconds east of UTC.
Sourcepub fn add_module(&mut self, name: &str, code: impl AsRef<[u8]>)
pub fn add_module(&mut self, name: &str, code: impl AsRef<[u8]>)
Registers module name for require (Libs::REQUIRE): require(name) compiles
code as chunk @name (unless package.loaded or package.preload has it first).
The host’s copy is not counted against the memory limit; what compiling it makes is.
Sourcepub fn add_module_source(&mut self, name: &str, source: ModuleSource)
pub fn add_module_source(&mut self, name: &str, source: ModuleSource)
Registers module name with its own origin (see ModuleSource).
Sourcepub fn set_module_loader(
&mut self,
loader: Option<impl Fn(&str) -> Option<ModuleSource> + Send + Sync + 'static>,
)
pub fn set_module_loader( &mut self, loader: Option<impl Fn(&str) -> Option<ModuleSource> + Send + Sync + 'static>, )
Sets the loader require asks for modules not registered with add_module
(None removes it). A name that is not UTF-8 is never asked for.