Error while using stack() with empty list Any[ ]

Hello everyone,

This is probably a very naive question but I don’t understand why i’m getting error in this case when i expect it to run perfectly. So In first example when I put main loop in test function I get error …while in second attempt when i keep it out it works perfectly.
I think both cases should work.

MWE:

aaa = []


function fill_aaa(m)

    for i in 1:10
        push!(aaa, (i, "a", i+m))
    end
end

function test(aaa)
 
    for i in 1:5
        aaa = []      # I want it to be empty for each iteration  
       fill_aaa(i)
       stack(aaa, dims = 1)

    end

end

test(aaa)

Output:

ERROR: ArgumentError: `stack` on an empty collection is not allowed
Stacktrace:
 [1] _empty_stack(::Int64, ::Vararg{Any})
   @ Base ./abstractarray.jl:2903
 [2] _stack(dims::Int64, ::Base.HasShape{1}, iter::Vector{Any})
   @ Base ./abstractarray.jl:2810
 [3] _stack
   @ ./abstractarray.jl:2799 [inlined]
 [4] stack
   @ ./abstractarray.jl:2767 [inlined]
 [5] test(aaa::Vector{Any})
   @ Main ./Untitled-1:17
 [6] top-level scope
   @ Untitled-1:22

now if i remove function and just run loop—

for i in 1:5
    aaa = []
    fill_aaa(i)
    stack(aaa, dims = 1)

end

Output: This is exactly what I want.

julia> aaa
10-element Vector{Any}:
 (1, "a", 6)
 (2, "a", 7)
 (3, "a", 8)
 (4, "a", 9)
 (5, "a", 10)
 (6, "a", 11)
 (7, "a", 12)
 (8, "a", 13)
 (9, "a", 14)
 (10, "a", 15)

Your function fill_aaa(i) captures the global variable aaa. It should take the empty collection that it is filling as an argument, i.e.

function fill_collection(x, m)
    for i in 1:10
        push!(x, (i, "a", i+m))
    end
end
3 Likes

it solves problem in MWE but still facing same issue in actual function :(. Maybe there is something else causing this issue.