noib3/nvim-oxi

[help] How to call other lua plugin exposed methods

Closed this issue ยท 4 comments

yyy33 commented

Like I want to develop my own plugin based on telescope, is it possible to use nvim-ox? Thanks

Hello ! I've got the same question. ๐Ÿ˜„

Moreover I think that it would be a good example.

Ok so after searching a couple hours, I understood that I was supposed to use mlua. Here is a small example :

// You must add `mlua` as a dependency in your Cargo.toml file.
use mlua::prelude::{LuaFunction, LuaTable};

use nvim_oxi::{self as oxi, Dictionary, Function};

// I don't understand yet what is this `_none` parameter.
// I added it and it's working but I guess I'll need to understand why at some point.
fn mlua_test(_none: ()) -> oxi::Result<()> {
    // You must also add feature `mlua` for nvim_oxi to your `Cargo.toml` as well.
    let lua = oxi::mlua::lua();

    // `lua.globals()` returns a reference to the global table of the Lua state.
    // `LuaFunction` is the type of what you `get` from the global table.
    // In this case it's a Lua function.
    let require = lua.globals().get::<_, LuaFunction>("require")?;

    // You can call this fuction like this to get the `telescope.builtin` table.
    let telescope_builtin: LuaTable = require.call("telescope.builtin")?;

    // I think that you get the point now.
    let find_files = telescope_builtin.get::<_, LuaFunction>("find_files")?;
    find_files.call(())?;

    Ok(())
}

#[oxi::module]
pub fn my_module() -> oxi::Result<Dictionary> {
    let mlua_test = Function::from_fn(mlua_test);
    Ok(Dictionary::from_iter([("mlua_test", mlua_test)]))
}

After installing it, you can do:

nvim -c "lua require'my_module'.mlua_test()"

I guess that you can go there for more in depth mlua usage -> https://github.com/mlua-rs/mlua

noib3 commented

// I don't understand yet what is this _none parameter.

You need to add it because Function::from_fn() accepts a closure (or a function in this case) whose argument implements Poppable. If your function doesn't take any arguments you can just use (), just like you did.

noib3 commented

I'll close this as completed but feel free to re-open it if you still have questions.