Edgar Klerks
Edgar Klerks

Reputation: 1537

For a new index from two indexes in a for loop

I was working on lua and looped over two tables and wanted to create a new table out of it, with no nil values in it. So this is basically a cross product. E.g:

 {1,2,3} x {3,4,5} -> {1*3,1*4,1*5,2*3,2*4,2*5,3*3,3*4,3*5}

Of course this is not hard to do:

  t = {1,2,3}
  s = {3,4,5}
  xs = {} 
  q = 1 
  for i,h in ipairs(t) do 
      for j,k in ipairs(s) do 
          xs[q] = h * k 
          q = q + 1 
      end 
  end 

We keep a counter q and add 1 every iteration. And this works fine. However is it also possible without a counter? Can I fill up x so with just i and j such that there are no gaps in x?

  t = {1,2,3}
  s = {3,4,5}
  xs = {} 

  for i,h in ipairs(t) do 
      for j,k in ipairs(s) do 
          q = f(i,j) -- <- I want to know if f is possible to write
          xs[q] = h * k 
      end 
  end 

I would say not, at least I was not able to find one myself easily.

EDIT: It is possible though if I am allowed to use the size of s.

    s = {1,2,3}
    t = {4,5,6} 
    xs = {} 

    for i,h in ipairs(s) do 
      for j,k in ipairs(t) do 
         q = i + (j - 1) * #t  
         xs[q] = h * k 
      end 
    end

Upvotes: 1

Views: 146

Answers (1)

Nifim
Nifim

Reputation: 5021

You can use table.insert, there is no reason to specify the index in your case.

s = {1,2,3}
t = {4,5,6} 
xs = {} 

for i,h in ipairs(s) do 
    for j,k in ipairs(t) do  
       table.insert(xs, h * k)
    end 
end
for _, v in ipairs(xs) do
    print(v)
end

Resource on insert:

https://www.lua.org/pil/19.2.html

Upvotes: 1

Related Questions