Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain why unpack() returns different results in Lua

Tags:

lua

lua-table

The following script finds prime numbers in a range from 1 to 13. When I explicitly iterate over the table that contains the results I can see that the script works as expected. However, if I use unpack() function on the table only the first 3 numbers get printed out.

From docs: unpack is "a special function with multiple returns. It receives an array and returns as results all elements from the array, starting from index 1".

Why is it not working in the script below?

t = {}
for i=1, 13 do t[i] = i end

primes = {}
for idx, n in ipairs(t) do
  local isprime = true
  for i=2, n-1 do
    if n%i == 0 then
      isprime = false
      break
    end
  end
  if isprime then
    primes[idx] = n
  end
end
print('loop printing:')
for i in pairs(primes) do
  print(i)
end
print('unpack:')
print(unpack(primes))

Running

$ lua5.3 primes.lua
loop printing:
1
2
3
5
7
13
11
unpack:
1   2   3
like image 739
minerals Avatar asked Dec 12 '25 13:12

minerals


1 Answers

Change

primes[idx] = n

to

primes[#primes+1] = n

The reason is that idx is not sequential as not every number is a prime.

like image 76
tonypdmtr Avatar answered Dec 16 '25 02:12

tonypdmtr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!