Menu
CoddyTech

Values and Table Identity

Lesson 10 of 48 in Coddy's Lua for C Developers course.

C cannot compare entire structs with ==. Compare their fields when you want value equality, or compare pointers when you want to know whether two pointers identify the same object. Plain Lua tables also have identity: two newly constructed tables are distinct even when all their fields contain equal values.

The C example explicitly compares both coordinate fields and reports a match. The Lua example compares the tables themselves and reports false. Assigning one table variable to another creates an alias, not a copy. An alias compares equal to the original table because both variables refer to the same table. Strings, unlike plain tables, compare by their contents in Lua.

C

#include <stdio.h>

struct Point { int x; int y; };

int main(void)
{
    struct Point a = {1, 2};
    struct Point b = {1, 2};
    puts(a.x == b.x && a.y == b.y ? "true" : "false");
    return 0;
}

Lua

local a = {x = 1, y = 2}
local b = {x = 1, y = 2}
print(a == b)

Porting trap

For coordinate equality, compare a.x == b.x and a.y == b.y. Lua equality also does not convert numeric text: "3" == 3 is false.

challenge icon

Challenge

Easy

Input is four integer lines x1, y1, x2, y2. Build two coordinate tables and return same when both corresponding fields match, otherwise different.

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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for C Developers

Practice on your own: Online Lua compiler