Skip to main content

Crate kevy_lua_host

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 type T (kevy’s Store for the production wiring; an arbitrary type in tests).
  • LuaHost::new(dispatch_fn) builds a kevy-lua Bridge whose dispatch closure does with_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 to Bridge::eval, and restore the previous slot after. A Drop guard ensures the restore even on panic.
  • with_current::<T> dereferences the pointer only when the slot’s type id is T’s, and empties the slot while its closure runs. The pointer is only ever installed while the outer &mut T is borrowed mutably by LuaHost::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::Bridge plus the scoped-pointer plumbing.

Functions§

with_current
Run f with a mutable borrow of the currently-set host context.
with_thread_host
Run f against this thread’s lazily-built LuaHost<T>.