Crate kevy_lua_host
Expand description
Scoped-borrow bridge between kevy_lua::Bridge and a host-owned
mutable shard state (Store, KeyspaceStore, anything 'static).
kevy-lua’s dispatch closure type is
Fn(&[&[u8]], bool) -> Vec<u8> + 'static. The 'static bound is
mandatory — luna-core stores the closure as Vm userdata (Any + 'static).
That makes it impossible to capture &mut T directly. This crate
offers a tiny LuaHost<T> wrapper that re-introduces the borrow via
a scoped thread-local pointer set inside LuaHost::eval and cleared
right after. The dispatch closure consults the pointer.
use kevy_lua_host::LuaHost;
// the host state the script's redis.call reaches: here, a call counter
let mut host = LuaHost::<u32>::new(|calls, _argv, _read_only| {
*calls += 1;
b":7\r\n".to_vec()
});
let mut calls = 0;
host.eval(&mut calls, b"return redis.call('GET', KEYS[1])", &[b"k"], &[]);
assert_eq!(calls, 1);§Safety contract (read this if you touch the unsafe)
LuaHost<T>parameterises over the host context typeT(kevy’sStorefor the production wiring; an arbitrary type in tests).LuaHost::new(dispatch_fn)builds a kevy-luaBridgewhose dispatch closure doeswith_current::<T>(|t| dispatch_fn(t, argv, ro)). The closure carries NO captured state of its own — it just reads the scoped pointer.LuaHost::eval(&mut self, &mut T, …)(and friends) install(ctx as *mut T, TypeId::of::<T>())BEFORE delegating toBridge::eval, and restore the previous slot after. ADropguard ensures the restore even on panic.with_current::<T>dereferences the pointer only when the slot’s type id isT’s, and empties the slot while its closure runs. The pointer is only ever installed while the outer&mut Tis borrowed mutably byLuaHost::eval, and lent to one closure at a time, so no aliasing exists.- kevy is single-threaded per-shard — every shard owns its own
LuaHost<T>and runs on a dedicated thread. The thread-local gives correct isolation without any synchronisation overhead.
The unsafe footprint is one unsafe { &mut *p } inside
with_current plus the Cell::set(ptr) ergonomics. Audit it on
every commit touching this file.
Structs§
- LuaHost
- kevy-side per-shard Lua host. Wraps a
kevy_lua::Bridgeplus the scoped-pointer plumbing.
Functions§
- with_
current - Run
fwith a mutable borrow of the currently-set host context. - with_
thread_ host - Run
fagainst this thread’s lazily-builtLuaHost<T>.