Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I shift all of the tables down after removing a table?

Tags:

lua

lua-table

In this code:

t = {
    num = '',
}

t[0].num = '0'
t[1].num = '1'
t[2].num = '2'

Is there a way for me to delete t[0], then shift all of the table's values down, so that afterword it looks like this:

t[0].num = '1'
t[1].num = '2'

Example with imaginary functions:

t = {
    num = '',
}

t[0].num = '0'
t[1].num = '1'
t[2].num = '2'

for i=0,tableLength(t) do
    print(t[i])
end
--Output: 012

remove(t[0])

for i=0,tableLength(t) do
    print(t[i])
end
--Output: 12
like image 272
DinoNuggies Avatar asked Oct 28 '25 21:10

DinoNuggies


1 Answers

t = {
    num = '',
}

t[0].num = '0'
t[1].num = '1'
t[2].num = '2'

This code will cause errors for indexing t[0], a nil value.

t only has one field and that is t.num

You need to do something like this:

t = {}
for i = 0, 2 do
  t[i] = {num = tostring(i)}
end

if you want to create the desired demo table.

As there are many useful functions in Lua that assume 1-based indexing you I'd recommend starting at index 1.

local t = {1,2,3,4,5}

Option 1:

table.remove(t, 1)

Option 2:

t = {table.unpack(t, 2, #t)}

Option 3:

t = table.move(t, 2, #t, 1, t)
t[#t] = nil

Option 4:

for i = 1, #t-1 do
  t[i] = t[i+1]
end
t[#t] = nil

There are more options. I won't list them all. Some do it in place, some result in new table objects.

like image 167
Piglet Avatar answered Oct 31 '25 11:10

Piglet