Before this lesson, complete lua-control-functions.
This course runs standard Lua 5.5 with its standard library. Game engines, LuaJIT and embedded host APIs are outside this sequence.
A Lua table maps keys to values and also represents ordinary sequences. A conventional dense sequence uses integer keys starting at one with no holes. Nil means absence: assigning nil removes a key. False, zero and an empty string are present values. Keep that distinction when filtering records or deciding whether a field exists.
Apply the contract
The length operator is dependable for a dense sequence, but a table with holes can have multiple borders. Do not use # to recover the intended extent of sparse data. In this lab, the caller supplies n explicitly, and the function visits every integer index from one through n. Append each non-nil value to a separate dense output. Since that output has no holes, result[#result+1] = value has the intended append behavior.
local packed=table.pack("a",nil,false)
print(packed.n)
for i=1,packed.n do print(i,type(packed[i])) end
local alias=packed
alias[1]="changed"
print(packed[1])Reason about the edge cases
Choose iteration to match the contract. ipairs visits consecutive integer keys and stops at the first absent entry. pairs traverses present keys without promising numeric order, and may also see non-sequence fields. Neither replaces a numeric loop over a supplied extent when holes matter. Tables are reference values: copying a variable copies a reference to the same table rather than cloning its entries. The compact function must construct a new result instead of editing the input as a side effect. Tests include false between missing entries, a value exactly at index n and a field beyond the requested extent.
Practice
Implement M.compact(values, n): scan integer keys 1 through n and return a dense sequence containing the non-nil values in order. Preserve false, zero and empty strings. Return a new table and leave all input entries unchanged, including keys outside the specified range. n is a nonnegative integer; never infer it from the length operator on the input table.
Run sample starts again from the first public fixture and grants no mastery evidence. Submit checks all fixtures, including edge cases. Read the specification before editing; the bug and fill phases share the build’s contract. Flashcards reinforce recall on a separate schedule.