Sets and Membership
Lesson 24 of 48 in Coddy's Lua for C Developers course.
C has no standard set container. A small set can use an array with an explicit duplicate check, while a larger set usually needs a more efficient lookup structure. Lua tables provide convenient membership lookup: store true at each member key. Repeating an insertion replaces the same association, so it does not add another member. An absent key evaluates to nil; assigning nil removes membership. The examples consume three labels but count only two distinct values. The C version compares string contents with strcmp, not pointer addresses.
C
#include <stddef.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *labels[] = {"a", "a", "b"};
size_t distinct = 0;
for (size_t i = 0; i < sizeof labels / sizeof labels[0]; ++i) {
size_t j = 0;
while (j < i && strcmp(labels[j], labels[i]) != 0) {
++j;
}
if (j == i) {
++distinct;
}
}
printf("%zu\n", distinct);
return 0;
}Lua
local seen = {}
for _, label in ipairs({"a", "a", "b"}) do
seen[label] = true
end
local count = 0
for _ in pairs(seen) do
count = count + 1
end
print(count)Porting trap
Count table members with pairs or maintain a separate count when inserting new keys. The length operator is for sequence boundaries and cannot count a set of arbitrary string keys.
Challenge
EasyInput lines are labels. Return the number of distinct labels. Repeated labels count once; empty input returns zero.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules5Tables as Collections
Arrays to Dense TablesRecords and Dynamic KeysSets and MembershipAliasing and Shallow CopiesRecap: Count InventoryPractice on your own: Online Lua compiler