Menu
CoddyTech

Independent Instance Tables

Lesson 35 of 48 in Coddy's Luau for C# Developers course.

C# instance field initializers can create a fresh collection per object, while static collections are shared. Luau constructors must create fresh nested tables for independent mutable state. A new outer table alone is insufficient if its field refers to a shared collection.

C# comparison

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var a=new Bag(); var b=new Bag(); a.Items.Add("x"); Console.WriteLine(b.Items.Count);
class Bag {public List<string> Items=new List<string>();}

Luau behavior

Store each instance collection in its own freshly allocated table. A shared methods table is useful; a shared mutable items table is usually not. table.clone of an outer instance still shares nested items, so copying the outer record alone does not establish ownership.

local function bag() return {items={}} end
local a,b=bag(),bag()
table.insert(a.items,"x")
print(#b.items)

Expected Luau output:

0
challenge icon

Challenge

Easy

Implement bags with an items table and an add(label) method. Input lines are labels added only to the first of two new bags. Return firstCount:secondCount. Empty input is valid.

Edit app.luau, model.luau. The visible locked main.luau 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.

Public API checks: Each new bag starts empty. add(label) appends the exact label, keeps duplicates and does not affect another bag. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local Model=require("./model")
local a,b=Model.new(),Model.new()
assert(#a.items==0 and #b.items==0,"new bags start empty")
a:add("x");a:add("x")
assert(#a.items==2 and a.items[1]=="x" and a.items[2]=="x","add preserves labels and duplicates")
assert(#b.items==0,"bag items must be independent")
end
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 Luau for C# Developers

Practice on your own: Online Luau compiler