Skip to content

Question: Is MetaMethod::IPairs missing for lua54? #635

Closed

Description

@jeremychone

I think I'm missing something. I'm using the lua54 feature, I have user data, and I would like to implement custom pairs and ipairs.

I can do that for pairs with MetaMethod::Pairs, but MetaMethod::IPairs is only enabled for the lua52 and luajit52 features.

Here is an example I would like to create:

methods.add_meta_method(MetaMethod::IPairs, |_, _, ()| -> Result<()> {
    Err(Error::RuntimeError("attempt to iterate over ...".into()))
});

What am I missing?

Activity

  1. khvzak commented on Aug 31, 2025

    @khvzak
    Member

    Lua 5.4 does not support __ipairs metamethods (it was removed since 5.3).

    You can use __index instead:

    struct MyUserData(i32);
    
    impl LuaUserData for MyUserData {
        fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
            methods.add_meta_method(LuaMetaMethod::Index, |_lua, this, k: i32| {
                if k < this.0 {
                    return Ok(Some(k * k));
                }
                Ok(None)
            });
        }
    }
    
    lua.load(
        r#"
        my_ud = ...
        for i, x in ipairs(my_ud) do
            print(i, x)
        end
    "#,
    )
    .call::<()>(MyUserData(5))
    .unwrap();

    or simply provide your own iterator function.

    If you want to remove ipairs support, then your __index should return a error for integer keys.

  2. locked and limited conversation to collaborators on Aug 31, 2025
  3. converted this issue into a discussion #636 on Aug 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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