Given a table with an arbitrary length, what's the most efficient way to insert a value at the first empty index?

My current method is to loop over the table until an index is nil, then set that index to the given value.


local foo = {'A', 'B', 'C', 'D', 'E'}
foo[3] = nil

function insertFirstEmpty(arr, val)

	for index = 1, #arr do
		if not arr[index] then
			arr[index] = val
			return
		end
	end

	table.insert(arr, val)

end

insertFirstEmpty(foo, 'F')

print(foo[3]) --"F"

Also, is there any benefit to doing this instead of just inserting the value to the end of the array? Am I preventing a memory leak or making my program more efficient?

2 comments

0

It won't do much, maybe a little more data will be taken up but that is fine... You can do either one, adding more to the table or overwriting the existing index

0

Well assuming I add and remove items in the table arbitrarily, and the program runs indefinitely, I'm afraid of memory leaks