lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mar 30, 2013, at 1:35 PM, Ico <lua@zevv.nl> wrote:

> * On Sat Mar 30 17:33:00 +0100 2013, Mason Mackaman wrote:
> 
>> why does 'f()' remove all entries of 'a'? Is that something I coded 
>> into 'f()' or is that something Lua does with functions?
> 
> Sorry, I wasn't quite clear:
> 
> The culprit is in the line
> 
>  local newset,cloneset={},set

He might have meant to do it that way?

Mason: you're clearing it because you have this:

    table.remove(cloneset)

...and cloneset truly points to the same table as 'a', so it's removing the entries of the same table. (you called it 'cloneset', but it's not a clone, it's the original)

That would all be ok if you then ultimately replaced 'a' with the newset table, but you don't, because this:

    function g(set)
        set=f(set)
    end

...changes the g() function's local 'set' to point to the same table as 'newset', but doesn't change the 'a' to be that new table.  It just changes the local variable 'set' to point to the thing returned by f(), instead of what was passed in as the arg to g().

So do this instead:
    function g(set)
        return f(set)
    end

    a={1,2,3,4,5,6,7,8,9}
    a = g(a)
    print(#a)

OR, if your goal is to hide the re-ordering of the original 'a' table's members, then do one of these instead:

    --------------------
    -- the brute-force approach
    --------------------
    function f(set)
        local newset = {}
        local ix = #set
        -- fill newset with reverse-order of set
        for x=1, ix do
            newset[x] = set[ix]
            ix = ix - 1
        end
        -- replace set's values with newset's
        for i,v in ipairs(newset) do
            set[i] = v
        end
    end

    a={1,2,3,4,5,6,7,8,9}
    f(a)
    print(#a)  --> 9
    print(unpack(a))  --> 9 8 7 6 5 4 3 2 1

    --------------------
    -- the less-brutish approach?
    --------------------
    function f(set)
        for i=1, #set do
            table.insert(set, i, set[#set])
            table.remove(set)
        end
    end

    a={1,2,3,4,5,6,7,8,9}
    f(a)
    print(#a)  --> 9
    print(unpack(a))  --> 9 8 7 6 5 4 3 2 1


-hadriel