For loop skips after receiving a nil value from a table

I have a simple code as shown below:

local myTable = {2, "true", "nah", nil, false}

for index, value in ipairs(myTable) do
	print(index, value)
end

When I run the code, the output shows:

  22:42:01.511  1 2  -  Server - VariadicFunctions:18
  22:42:01.511  2 true  -  Server - VariadicFunctions:18
  22:42:01.511  3 nah  -  Server - VariadicFunctions:18

The moment my for loop reaches the fourth value in the table, that is nil, it skips that value and does not print the fifth value in the table which is false. Why does this happen? How does for loops work in this case?

Thanks.

No worries, Roblox Studio’s AI assistant has saved the day! Here’s what it said:

Behavior with nil Elements:
It’s important to note that ipairs stops iterating at the first nil value it encounters. This is a characteristic behavior of ipairs in Lua, as it is designed for sequentially indexed tables without gaps. Since nil is used in Lua to represent the absence of a value, encountering nil in a sequence signals the end of the array part of a table to ipairs.

Given the above points, here’s what happens when the code runs:

  • The loop starts at the first element of myTable, which is 2, and prints 1 2 to the console (1 is the index, and 2 is the value).
  • It then moves to the second element, “true”, and prints 2 true (note that “true” is a string, not a boolean value, hence printed as is).
  • The third iteration prints 3 nah, corresponding to the third element.
  • Upon reaching the fourth element, which is nil, ipairs stops iterating. This means the loop ends prematurely, and the last element (false) is never reached or printed.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.