Tables as Instances
Lesson 33 of 48 in Coddy's Lua for GDScript Developers course.
GDScript creates script instances with new, which calls the class initializer _init. Lua has no class declaration or automatic initializer. A conventional constructor is an ordinary function such as Model.new(n) that allocates a table and returns it. A metatable can give that table access to shared methods: set Model.__index = Model, then attach Model to each new instance. Store changing values directly on the instance. Each constructor call must allocate its own table. The examples create two independent counters and change one and inspect both values, without adding either object to Godot's scene tree.
GDScript 4
extends SceneTree
class Counter:
var n
func _init(initial):
n = initial
func _init():
var first = Counter.new(4)
var second = Counter.new(7)
first.n = 9
print(str(first.n) + ":" + str(second.n))
quit()Lua 5.1
local Counter = {}
Counter.__index = Counter
function Counter.new(initial)
return setmetatable({n = initial}, Counter)
end
local first = Counter.new(4)
local second = Counter.new(7)
first.n = 9
print(first.n .. ":" .. second.n)Porting trap
Lua does not invoke a function merely because it is named _init. Call initialization code from your constructor and return the new instance explicitly.
Challenge
EasyIn model.lua, 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.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: 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 Lua for GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple 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
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler