Why does this code crash?

Title says it all:

local t = {1}
for _ in next, t do
   table.insert(t, 1)
end

Because you are looping infinite, if you put ipairs instead of next I think it will work.

When something changes in a table, while using next it will start again, using ipairs it will stop

You need to add a key and a value in your iteration:

for _,value in next, t do

You don’t need to.

In this instance _ is the key and will run. It still runs out of memory. I’m testing things right now.

1 Like

Just tested ipairs as well, still gives me a “Not enough memory” output.

He doesn’t need 100% to put it, what you said is like a loop like this:

for i = 1,10 do
      print("works")
end

i is useless and you should use _

This code runs indefinitely.
Essentially, each time you add an item to the table, the table grows bigger, so it keeps running through that index in the table, then the next, and the next, and so on until you run out of memory or crash.

What are you trying to use this for?

To add on, since tables are objects they are passed by reference, so it’s not like any copies are being made.

1 Like