Question on Table Manipulation

I have a table here:

myTable = {{},{},{}}

so I insert items in it like this:

myTable[1][1] = "Question" myTable[2][1] = "Question Time" myTable[3][1] = "Time Question"

so here’s the catch, when I use “table.remove” it adjusts the table, like this:

table.remove(myTable,1)

and now when I use #myTable, it returns to 2, what I want is myTable[1] will be nil or just an empty cell( {} ), so when I use #myTable, it will return 3

To do that, don’t use table.remove.    Just set mytable[1] = {}, or mytable[1]=nil.

That will remove the reference to the previous contents and make it eligible for garbage collection if the reference count is 0.

Memory management/garbage collection is one of those things that you can get away with ignoring 90% of the time with ok results, but It’s good that you’re thinking about it up front.   It’s worth your time to learn and understand how it works early on.

Keep in mind that if you do:

t = {}

t[1] = “hello”

t[2] = nil

t[3] = “world”

print(#t) will print “1” not “3”.  The # operator only counts numerically indexed entries up to the first nil.  You need table.maxn(t) in this case to get 3 back.

Okay guys thanks :slight_smile:

To do that, don’t use table.remove.    Just set mytable[1] = {}, or mytable[1]=nil.

That will remove the reference to the previous contents and make it eligible for garbage collection if the reference count is 0.

Memory management/garbage collection is one of those things that you can get away with ignoring 90% of the time with ok results, but It’s good that you’re thinking about it up front.   It’s worth your time to learn and understand how it works early on.

Keep in mind that if you do:

t = {}

t[1] = “hello”

t[2] = nil

t[3] = “world”

print(#t) will print “1” not “3”.  The # operator only counts numerically indexed entries up to the first nil.  You need table.maxn(t) in this case to get 3 back.

Okay guys thanks :slight_smile: