I got a table like so:
local values = {
[1] = "one",
[2] = "two",
[3] = "tree",
[4] = "four",
}
And I want to insert a value (not with table.insert()) in a specific location.local function add(table,index,element) for i = #table,index,-1 do table[i+1] = table[i] end table[index] = element return table end
Basically push the values at the position entered, ex:
add(values,3,"two point five")which ends up with a table like so
values = {
[1] = "one",
[2] = "two",
[3] = "two point five",
[4] = "tree",
[5] = "four"
}
Is the example function I provided good? Or can it be done a much more elegant and compact way?
This function does not work if the table got gaps.
I need a similar function to do the same but reverse, remove a index and pull the elements after towards it, so to speak.
Ex:
local function remove(table,index) local max = #table for i = index+1,max do table[i-1] = table[i] end table[max] = nil return table end
Which ends up with a table that looks like
remove(values,3)
values = {
[1] = "one",
[2] = "two",
[5] = "four"
}
Also while testing these functions I noticed that they don't only change the internal values from the arguments but also the initial table, the same way the table.sort() does. Why is that and how do I fix that?
Edited by akaJag, 18 November 2013 - 04:16 PM.













