Skip to content

pairs/ipairs metamethods should work with userdata #205

@CodeSmile-0000011110110111

Description

For a LuaList type I was trying to implement the Metamethod.IPairs and Pairs to enumerate the values in the list from within Lua using the standard pairs/ipairs functions.

However this fails:

Lua.LuaRuntimeException : Lua-CSharp: .../LuaListTests.lua:22: bad argument #1 to 'pairs' (table expected, got userdata))

The default Pairs and IPairs functions both read a table as the first argument:

    public async ValueTask<int> Pairs(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
    {
        var arg0 = context.GetArgument<LuaTable>(0);

This limits the use of Metamethod.Pairs and IPairs. It should work with both LuaTable and ILuaUserData arguments.
According to this user Lua 5.2 does support pairs/ipairs to work with userdata.

On first sight it might work by changing to GetArgument<ILuaUserData> and then testing for whichever interface implements TryGetValue(key, value). Not sure if this will require ILuaUserData to define that. It will also require LuaTable to implement ILuaUserData (it already does anyway).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions