Is there a cross between pairs and ipairs?

I want to have something like this:

for i,k,v in ikpairs(dictionary) do

Is this a thing / an alternative?

What are you trying to do? or trying to accomplish?

Get the index, key and value of a dictionary

the key is the index, if you mean you want a numeric index dictionarys aren’t ordered nor have any numeric indices that a property of dictionarys

String dictionaries. Something like this:

local dictionary = {
    ["this is an item"] = 5;
    ["another item"] = 10;
    ["third item"] = 2;
}
for i,k,v in ikpairs(dictionary) do
     print(i,k,v)
    -- this should print:
    -- 1,"this is an item",5 
    -- per item
end

You can sort of do something like that by constructing the dictionary as a 2D list:

local dictionary = {
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
}

for i, list in ipairs(dictionary) do
    local k, v = table.unpack(list)
    -- code
end
3 Likes

I know I am saying that dictionaries are not ordered there no gauntuee that “This is an item” will be the first element that pops up

1 Like

It wouldn’t matter the order of them

I’m gonna test this but this seems like the solution

What the purpose of having a numeric index then?

If the ordering doesn’t matter, another way you could go about it is just incrementing a variable each iteration:

local dictionary = {
    ["this is an item"] = 5;
    ["another item"] = 10;
    ["third item"] = 2;
}

local i = 0
for k, v in pairs(dictionary) do
    i += 1
    -- code
end

If this is what you really want, this would be how you define the iterator:

local function ikpairs(tabl)
    local lastk = nil
    local function iknext(tbl, i)
        i += 1
        local k, v = next(tbl, lastk)
        lastk = k
        if k == nil then
            return nil
        else
            return i, k, v
        end
    end

    return iknext, tabl, 0
end

Edit: This actually wouldn’t work because i would be passed in, not k.

Edit 2: This one probably works.

Edit 3: This one definitely works.