Determine position of value in table

Greetings, I have a for loop that is to replace nil within a table with multiple numbers.
This is the layout of the dictionary

["rooms"] = { -- it isn't called rooms, there's a variable named rooms. for now we'll keep it like this
     ["Penthouse"] = {101, nil, 109, 201, nil, 209},
     --there are more dictionaries bellow
}

It should replace nil with all the numbers between the one before and the one after.
It works for the first nil (101-109) but the second nil it doesn’t work.

i is the Dictionary “Penthouse”
k is the room number

I managed to narrow down the problem, the “new” value no longer points to the nil.
{101, nil, 104, 205, nil, 208}

then it becomes

{101,102,103,104,205,nil,208}
How can I make the “new” variable become the position of the new nil?
I can’t come up with anything.
Btw, it can have more nils after this, not limited to 2 nils so #table - 1 won’t work
Thanks in advance,

function fixRooms()
	for i=1, length(rooms), 1 do
		local roomType = rooms[roomTypes[i]]
		local new = 1
		for k=1, #roomType, 1 do
			if k > 1 and #roomType >= new + 2 then
				if roomType[new+1] == nil or roomType[new+1] == "nil" then
					local start = roomType[new]
					local ending = roomType[new+2]
					for o=ending-1, start+1, -1 do
						table.remove(roomType,tonumber(roomType[new+1]))
						table.insert(roomType,new+1,o)
					end
					new = new+3
				end
			end
			wait()
		end
	end
end
2 Likes

When you table.insert, it shifts all the values up one index if it needs to, meaning that if there’s a nil value somewhere, the shifts don’t cascade beyond that and the nil “gap” gets filled. You’ll have to traverse the table backwards to avoid this.

Here's my solution:
function fillBetween(t)
    --Current index
    local i = #t - 1 --don't need to check the last value, because t[#t + 1] will always be nil
    
    --Traverse table backwards
    while i > 1 do
        
        --Search for nil values
        if t[i] == nil then
            --Start and end of number sequence
            local s, e = t[i - 1], t[i + 1]
            
            --Get rid of the nil value
            table.remove(t, i)
            
            for v = e-1, s+1, -1 do
                --[[Inserting at i pushes all subsequent values upwards. There will be no nil values above i because we're traversing t backwards. If we didn't, any nil values above i would be overwritten]]
                table.insert(t, i, v)
            end
        end

        --Decrement index to traverse backwards
        i = i - 1
    end

    return t
end

print(table.concat( fillBetween{101, nil, 109, 201, nil, 209}, ", " ))
Which outputs:

101, 102, 103, 104, 105, 106, 107, 108, 109, 201, 202, 203, 204, 205, 206, 207, 208, 209

1 Like