1

I have a code:

function subsets(t)
    local res={}
    local res_t={}
    function subs(i)
        if i>#t then
            res[#res+1]=res_t
            return 
        end
        res_t[#res_t+1]=t[i]
        subs(i+1)
        table.remove(res_t)
        subs(i+1)
    end
subs(1)
return res
end

i want it to return results which is table with tables with arrays but it returns me table with empty tables, idk if i wrote it right but res table is non-empty inside a function but empty as final result:

1   table: 000002721a66a3f0
2   table: 000002721a66a3f0
3   table: 000002721a66a3f0
4   table: 000002721a66a3f0
5   table: 000002721a66a3f0
6   table: 000002721a66a3f0
7   table: 000002721a66a3f0
8   table: 000002721a66a3f0

all this tables are empty, like all tables are overwritten by final table which comes out empty

i want to understand what's wrong with function, im new to programming and really appreciate some help

0

1 Answer 1

1

The reason is quite simple. Tables in Lua are passed by reference, therefore, res_t remains the same table throughout the entire process of calling subsets. You appended t[i], then removed it, so finally res_t is naturally empty.

When you need to use res_t as a result, you should clone it. Here is a concise method:

res[#res+1]={table.unpack(res_t)}
Sign up to request clarification or add additional context in comments.

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.