Menu
CoddyTech

Aliasing and Shallow Copies

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

C structure assignment copies member values. A copied integer is independent, but a copied pointer still points to the same object. Lua table assignment instead copies a reference to the entire table, so b = a aliases every field. To obtain a shallow copy, create a new table and copy its key-value associations. Scalar fields can then change independently, while nested tables remain shared references. The examples change the copy's scalar field and then change shared nested state. The original retains its scalar value but observes the nested update.

C

#include <stdio.h>
struct Record { int n; int *nested; };
int main(void) {
    int shared = 2;
    struct Record original = {1, &shared};
    struct Record copy = original;
    copy.n = 9;
    *copy.nested = 7;
    printf("%d:%d\n", original.n, *original.nested);
    return 0;
}

Lua

local original = {n = 1, nested = {value = 2}}
local copy = {}
for key, value in pairs(original) do
  copy[key] = value
end
copy.n = 9
copy.nested.value = 7
print(original.n .. ":" .. original.nested.value)

Porting trap

Do not translate C structure assignment into Lua table assignment when an independent outer record is required. A shallow copy also does not establish independent nested ownership; duplicate nested tables deliberately where needed.

challenge icon

Challenge

Easy

Input is an integer original value and integer replacement. Create a record, shallow-copy it, replace the copy value, and return original:copy.

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