Modules should be registered in luby not lb

This commit is contained in:
2025-06-26 13:46:39 +10:00
parent bcb734846d
commit 88ab48cddb
9 changed files with 41 additions and 111 deletions

View File

@@ -1,5 +0,0 @@
local task = require("lb:task")
function spawn(f, ...)
return task:spawn(f, ...)
end

View File

@@ -1,4 +1,3 @@
use crate::{chan::lb_chanlib, fs::lb_fslib, net::lb_netlib, task::lb_tasklib};
use derive_more::{Deref, DerefMut};
use luaffi::{Registry, Type};
use luajit::{Chunk, State};
@@ -15,15 +14,13 @@ pub struct Builder {
impl Builder {
pub fn new() -> Self {
let mut registry = Registry::new();
Self {
registry: Registry::new(),
}
}
registry
.preload::<lb_tasklib>("lb:task")
.preload::<lb_chanlib>("lb:channel")
.preload::<lb_fslib>("lb:fs")
.preload::<lb_netlib>("lb:net");
Self { registry }
pub fn registry(&self) -> &Registry {
&self.registry
}
pub fn module<T: Type>(&mut self, name: impl Display) -> &mut Self {
@@ -31,18 +28,11 @@ impl Builder {
self
}
pub fn registry(&self) -> &Registry {
&self.registry
}
pub fn build(&self) -> luajit::Result<Runtime> {
Ok(Runtime {
state: {
let mut s = State::new()?;
let mut chunk = Chunk::new(self.registry.done());
chunk.extend(include_bytes!("./runtime.lua"));
// println!("{chunk}");
s.eval(chunk.path("[luby]"), 0, 0)?;
s.eval(Chunk::new(self.registry.build()).path("[luby]"), 0, 0)?;
s
},
tasks: LocalSet::new(),
@@ -73,6 +63,9 @@ impl Runtime {
}
pub fn spawn<T: 'static>(f: impl AsyncFnOnce(&mut State) -> T + 'static) -> JoinHandle<T> {
// SAFETY: `new_thread` must be called inside `spawn_local` because this free-standing spawn
// function may be called via ffi from lua, and it is not safe to access the lua state within
// ffi calls.
spawn_local(async move { f(&mut STATE.with(|s| s.new_thread())).await })
}