1

I want to loop through a table that looks like this

function add(t, k, v, ...)
    if k ~= nil then
        t[k] = v
        t[#t+1] = k
        return add(t, ...)
    end
    return t
end

my_table = add({ }, "a", 5, "b", 4, "c", 3)

for i,k in ipairs(my_table) do
    local v = my_table[k]
    print(k, v)
end

Result:

a - 5

b - 4

c - 3

But I want to be able to loop through the table using the index, the key, and the value, so it looks like this:

1 - a - 5

2 - b - 4

3 - c - 3

Is this possible in Lua?

0

2 Answers 2

3

Iterator:

function triples(t)   
  local function next_triple(tbl, idx)
    idx = idx + 1
    local k = tbl[idx]
    if k ~= nil then 
      return idx, k, tbl[k]
    end
  end
  return next_triple, t, 0
end

Usage:

local a = {"q", "w", "e", q = 11, w = 22, e = 33}
for i, k, v in triples(a) do
  print(i, k, v)
end

Output:

1   q   11
2   w   22
3   e   33
Sign up to request clarification or add additional context in comments.

2 Comments

you could also use ipairs and print(i,v,a[v])
@Piglet - Yes. I don't know why OP don't like his own code.
2

An alternate implementation of Egor's triples function using coroutines:

function triples(t)
  return coroutine.wrap(function()
    for i, k in ipairs(t) do
      coroutine.yield(i, k, t[k])
    end
  end)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.