Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

New table.insert function?

Asked by
LuaQuest 450 Moderation Voter
8 years ago

I'm trying to re-write the table.insert function. Since table.insert uses rawset (which is the reason it doesn't invoke any metamethods), I'm trying to make my own table.insert function that sets a value to a table by creating a new index. Here's the problem:

My problem with this, is table.insert's second argument as it's position. When using the second argument as the position you're giving the value, table.insert pushes all other values up the list by 1. For example:

local t = {'a','b','c'}

table.insert(t,1,'z') -- this is basically what I'm trying to re-create

print(unpack(t)) -- output: 'z' 'a' 'b' 'c'

I've attempted to make a function for this, but only got this far:

local t = {'a','b','c'}

-- Basically just making a new reference to the table library, and a separate one for the insert function.

local table=setmetatable({},{
    __index=function(tab,k)
        if(k=='insert')then
            return function(tab,pos,val)
                if(type(pos)=='number')and(val)then
                    local n=0
                    for i=pos,#tab do
                        tab[i+1]=tab[i+n] -- the problem?
                        n=n+1
                    end
                    tab[pos]=val
                elseif(pos)and(not val)then
                    -- in this case, "pos" is the value
                    tab[#tab+1]=pos
                end
            end
        else
            -- If it's not the insert function, return the default from the given index.
            return table[k]
        end
    end
})

table.insert(t,1,'z')

-- The insert function above outputs:

-- 1 z
-- 2 a
-- 3 c

-- When it should be:

-- 1 z
-- 2 a
-- 3 b
-- 4 c

Or maybe the problem is with my for loop iterations, but I'm not sure.

So basically, I could shorten the question to this:

How could I make a function that can push each value in a list's numeric index, up by 1?

This has REALLY been an issue for me, and would help a lot considering I'm in specific need of something like this. Any small example or algorithm with minimal explanation would be very much appreciated. Thank you for reading.

Answer this question