Skip to content

How to handle Rust state? #130

@noib3

Description

@noib3

Hi, this might be a noobish question. I'm writing a Rust plugin for Lua and I was wondering what's the best approach to handle state on the Rust side.

For a basic example, I'm trying to write a require('mymodule').plus_one() function that increments the field of a Rust struct every time it's called. This is what I have rn, which doesn't compile.

use mlua::{Lua, Result, Table};
use std::sync::{Arc, Mutex};

struct State {
    foo: usize,
}

fn plus_one(state: &mut State) {
    state.foo += 1;
}

#[mlua::lua_module]
fn mymodule(lua: &Lua) -> Result<Table> {
    let state = Arc::new(Mutex::new(State { foo: 0 }));
    let state = &mut state.lock().unwrap();

    let plus_one = lua.create_function(|_, ()| Ok(plus_one(state)))?;

    let exports = lua.create_table()?;

    // Should increment `state.foo` by 1 on every `require('mymodule').plus_one()` call
    exports.set("plus_one", plus_one)?;
    Ok(exports)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions