Menu
CoddyTech

Independent Instance Tables

Lesson 35 of 48 in Coddy's Lua for GDScript Developers course.

A GDScript instance can initialize its own items array in _init, ensuring each bag owns a separate container. A Lua constructor must allocate its own items table for the same reason. Putting items = {} on the shared method table gives every instance the same fallback table through __index. Mutating that nested table changes shared state even if each outer instance table is separate. Allocate mutable collections inside the constructor, alongside other instance fields. Keep methods on the shared prototype, where sharing is intentional. These examples add labels only to the first bag and inspect the second bag to verify independence.

GDScript 4

extends SceneTree
class Bag:
    var items
    func _init():
        items = []
    func add(label):
        items.append(label)
func _init():
    var first = Bag.new()
    var second = Bag.new()
    first.add("key")
    first.add("map")
    print(str(first.items.size()) + ":" + str(second.items.size()))
    quit()

Lua 5.1

local Bag = {}
Bag.__index = Bag
function Bag.new()
  return setmetatable({items = {}}, Bag)
end
function Bag:add(label)
  table.insert(self.items, label)
end
local first, second = Bag.new(), Bag.new()
first:add("key")
first:add("map")
print(#first.items .. ":" .. #second.items)

Porting trap

A fresh outer instance is insufficient if its items field resolves to a shared prototype table. Allocate both the instance and its mutable items table per constructor call.

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.lua, model.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.

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 Lua for GDScript Developers

Practice on your own: Online Lua compiler