Tables as Instances
Lesson 33 of 48 in Coddy's Luau for Java Developers course.
Java constructors initialize class instances and enforce declared field and access rules. Luau constructor functions create fresh tables and attach shared behavior through metatables. Type aliases allocate neither instances nor fields. Assigning an existing table creates another reference to it.
Java comparison
import java.util.*;
import java.util.function.*;
import java.util.regex.*;
public class Main {
static class Item {int n; Item(int n){this.n=n;}}
public static void main(String[] args) throws Exception {
Item a=new Item(2),b=new Item(5); System.out.println(a.n+b.n);
}
}
Luau behavior
Luau has no class declaration. Build a fresh table in a constructor and attach a shared methods table through __index. A record type can document state, but only the constructor allocates each instance. Keep independently mutable fields in the new table.
local Item={}
Item.__index=Item
function Item.new(n) return setmetatable({n=n},Item) end
local a,b=Item.new(2),Item.new(5)
print(a.n+b.n)Expected Luau output:
7Challenge
EasyIn model.luau, implement Model.new(n) to create an instance holding n. The app creates two instances from two integer lines and returns their sum.
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: Model.new(n) must retain n on a fresh independent instance. 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(2),Model.new(-3)
assert(a.n==2 and b.n==-3,"Model.new must retain each supplied n")
a.n=9
assert(b.n==-3,"instances must own independent n state")
end
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 Luau for Java Developers
1First Luau Programs
Run Luau ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions7Objects and Owned State
Validation Before MutationTables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account Objects2Values and Decisions
Missing Fields and OptionalsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Luau compiler