I’m trying to write an app using gtk-rs, and I want to integrate Lua scripting into it, but I’m struggling to get the lifetimes to cooperate. The primary issue is that callback closures require a 'static
lifetime, which the Lua library is unable to provide due to being initialized at runtime. It looks like this has been discussed before, but with no solution.
As an MVP, here is my Cargo.toml
:
[package]
name = "gtk-lua"
version = "0.1.0"
edition = "2021"
[dependencies]
gtk = { version = "0.4", package = "gtk4" }
mlua = { version = "0.7", features = ["lua54"] }
And my main.rs
:
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow};
fn main() {
// Create a new application
let app = Application::builder()
.application_id("org.gtk-rs.example")
.build();
let lua = mlua::Lua::new();
// Connect to "activate" signal of `app`
app.connect_activate(|app| build_ui(&app, &lua));
// Run the application
app.run();
}
fn build_ui(app: &Application, lua: &mlua::Lua) {
// Create a window and set the title
let window = ApplicationWindow::builder()
.application(app)
.title("My GTK App")
.build();
let activate_focus_callback = lua.create_function(|_, ()| {
println!("Activate focus signal received");
Ok(())
}).unwrap();
window.connect_activate_focus(move |_| {
activate_focus_callback.call::<(), ()>(());
});
// Present window
window.present();
}
This is basically just the Hello World app, but with a Lua function defined as a callback on the window. When compiled, I get this error message:
Compiling gtk-lua v0.1.0 (/home/damien/Workspace/gtk-lua-test)
error[E0759]: `lua` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/main.rs:26:39
|
19 | fn build_ui(app: &Application, lua: &mlua::Lua) {
| ---------- this data with an anonymous lifetime `'_`...
...
26 | let activate_focus_callback = lua.create_function(|_, ()| {
| --- ^^^^^^^^^^^^^^^
| |
| ...is captured here...
...
31 | window.connect_activate_focus(move |_| {
| ---------------------- ...and is required to live as long as `'static` here
For more information about this error, try `rustc --explain E0759`.
error: could not compile `gtk-lua` due to previous error
Is there any way to be able to invoke a Lua-defined function within a GTK callback? I know that callbacks can basically happen whenever, and I need to promise to the compiler that Lua is still around, but it seems like something that should at least be doable with unsafe code, and while I can get it to compile, the result just segfaults.
Any tips on how to get this to work?