[Solved] Implementing Function Iterator in rlua

Hello,
I would like implement a function that will return an iterator that returns a new entry each time it is called in rlua.
Something like this :
for fname in dir(".") do print(fname) end

I found the solution in C implementation of lua,But unfortunately their API aren't available in rlua.
Could please give me some hint to implementing this in rlua ?

Thanks.

Iterators in Lua are functions that are repeatedly called, so to have an iterator like this, you need a function returning a function.

use rlua::{Error, Lua, Result, String};
use std::ffi::OsStr;
use std::fs;
use std::os::unix::ffi::OsStrExt;

fn main() -> Result<()> {
    let lua = Lua::new();
    lua.context(|ctx| {
        let dir = ctx.create_function(|ctx, path: String<'_>| {
            let mut dir =
                fs::read_dir(OsStr::from_bytes(path.as_bytes())).map_err(Error::external)?;
            ctx.create_function_mut(move |ctx, ()| {
                dir.next()
                    .map(|entry| {
                        ctx.create_string(
                            entry
                                .map_err(Error::external)?
                                .path()
                                .as_os_str()
                                .as_bytes(),
                        )
                    })
                    .transpose()
            })
        })?;
        ctx.globals().set("dir", dir)?;
        ctx.load(r#"for fname in dir("/tmp") do print(fname) end"#)
            .exec()?;
        Ok(())
    })
}
1 Like

So many thanks :bouquet::bouquet:.

A post was split to a new topic: Futures::stream question

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.