Where script state lives
A Defold game is many script instances sharing a few script modules. Where you put a piece of mutable state decides who can see it and change it — one component, every component of one script, every script in the game, or the whole Lua VM. This page walks those four tiers from narrowest to widest, each grounded in the Lua the toolchain actually emits.
This page is about placement. The typing model for self — how init infers it and how properties seed it — lives in Script lifecycle.
Per-instance state: self
State that each component instance owns belongs on self. init's returned object is copied onto self for that component instance, so two game objects running the same script keep independent values: decrement one object's self.health and the other's is untouched.
import { defineScript } from "@defold-typescript/types";
export default defineScript({
init() {
return { health: 100 };
},
update(self) {
self.health -= 1;
},
});Every object that mounts this script gets its own self.health. This is the default home for anything an instance must own a private copy of. The full typing model is in Script lifecycle.
Sharing state across instances of one script
A module-level let or const is not per-instance. Defold loads each script module once via require and caches the result, so a variable declared at module scope is created once and seen by every component instance of that script. The build makes the split visible — spawnCount is a module local, while health is written onto each instance's self:
import { defineScript } from "@defold-typescript/types";
// Module-level: one value, not per-instance.
let spawnCount = 0;
export default defineScript({
init() {
return { health: 100 };
},
update(self) {
self.health -= 1;
spawnCount += 1;
},
});local spawnCount = 0
function init(self)
-- self.health is set per instance
end
function update(____self)
____self.health = ____self.health - 1
spawnCount = spawnCount + 1
endspawnCount is a single Lua module local evaluated once at chunk scope; because the module is cached, that one value is shared by every component instance that runs this script. Reach for a module local only for constants or a deliberately-shared counter — keep anything each instance must own its own copy of on self.
Sharing state across different scripts: a module singleton
To share state across different scripts — a spawn registry, a score table, an event bus — put it in its own module and import it wherever you need it. Because every import lowers to a cached require, each script that imports the module sees the same table:
// registry.ts — one module, shared by every importer.
let spawned = 0;
const names: string[] = [];
export function register(name: string): void {
spawned += 1;
names.push(name);
}
export function spawnedCount(): number {
return spawned;
}// spawner.ts and hud.ts both import it and see the same state.
import { register, spawnedCount } from "./registry";import { register } from "./registry" lowers to a require that Defold caches once, so spawner.ts and hud.ts read and write the same spawned/names values. This is the idiomatic pattern for game-wide tracking — prefer it over raw globals: a module singleton is scoped, typed, and explicit about who depends on it.
Exporting a value from a script itself
A script does not have to hand its shared values to a separate module. A source that calls defineScript (or defineGuiScript/defineRenderScript) and exports runtime values builds into two files: the component resource the editor loads, and a companion Lua module beside it holding those exports.
// game/doors/door.ts — one source, two outputs.
import { defineScript } from "@defold-typescript/types";
export const DOOR_SPEED = 3;
export const state = { open: false };
export default defineScript({
init() {
state.open = true;
},
});build writes game/doors/door.ts.script and game/doors/door.lua. The component requires the companion rather than redeclaring its exports, so state is one table: the door's own init and any import { state } from "./doors/door" elsewhere read and write the same object. Values only the script uses stay in the script.
The companion takes the whole dependency closure of the exports — a private helper an exported function calls moves with it, as does a sibling of the same const a = 1, b = 2; declaration, and an export list such as export { value as speed }; travels with the values it names. An import the closure needs is copied rather than moved: the companion takes its own require of that module, and Lua's module cache makes it the same table the script holds. That is why the two shapes below are rejected: they are the cases where "one definition" and "runs in the script" cannot both hold.
One limit is worth knowing before you lean on this:
- A dot in the source name is not supported.
foo.bar.tscompiles tofoo.bar.luawhile everyrequireof it saysfoo_bar— rename the source.
A configured outDir needs no special handling: the companion lands under the outDir and the component requires it by the path it was written to.
When the build sends you here
build and watch reject a script whose exported values cannot be told apart from its lifecycle hooks. The clearest case is a private binding an exported function reassigns while a hook also reads it:
// door.ts — rejected.
import { defineScript } from "@defold-typescript/types";
let count = 0;
export function increment(): void {
count++;
}
export default defineScript({
update() {
increment();
print(count);
},
});The error names count and both lines that reach it. A companion cannot carry this: count would live in the module while the hook read a copy, so the script would never see increment's update. Move count and increment into a module of their own — the singleton above — and import them from the script. What counts is the rebinding, not how it is spelled: count = 1, [count] = [1], ({ count } = …) and for (count of …) are one shape. Writing through a binding — state.ready = true — is not, because both sides hold the same table, which is exactly why an exported object is safe to share.
The other rejected shape is an effectful top-level statement — a call rather than a literal — with any exported declaration, or anything one of them reaches, below it. Move it below them all, or into init.
The block setup-debug writes is the one exception. The component runs its gated lldebugger.start() before it loads the companion, so the debugger is attached before any exported value is built. Once you edit that block, it counts as ordinary top-level work again, and the error says to run defold-typescript setup-debug, which restores it.
Truly global variables: declare global
The widest tier is a bare Lua global, shared across the entire VM — every script, no import. You reach it from TypeScript with declare global. The declaration itself emits no Lua; the first assignment creates the global at runtime:
declare global {
var FOO: number;
}
export function bump(): number {
FOO = FOO + 1;
return FOO;
}local ____exports = {}
function ____exports.bump()
FOO = FOO + 1
return FOO
end
return ____exportsNote what is not there: no local FOO, no initializer, no ____exports. prefix. FOO is a raw Lua global — broader than a cached module local, because it is scoped to no module at all. TypeScriptToLua emits nothing for the declare global block itself; it only tells the type-checker the global exists, and the first assignment creates it VM-wide. Reach for this only for genuine engine or Lua globals you cannot type any other way; for app state, prefer a module singleton.
Choosing where state lives
| You want state… | Put it… |
|---|---|
| owned by one component instance | on self |
| shared by every instance of one script | a module-level let/const |
| shared across different scripts (app state) | a module singleton (import a shared module) |
| visible to the whole Lua VM, no import | declare global — real Lua/Defold globals only |
A rule of thumb: self for per-instance state; a module singleton for deliberately-shared app state; msg.post or a dedicated manager object when ownership and lifecycle matter; declare global only for real Lua/Defold globals. One hot-reload caveat: a reload keeps state — self (see Hot reload and on_reload) and module state alike. When a changed module reloads, Defold re-runs its code, but require keeps returning the first table, so every importer keeps the old functions and any value it read from the module at load time.
See also
- Script lifecycle — typing
self,on_message, andon_inputwithdefineScript. - TypeScript vs Lua — the
require/importmapping and thedeclare globallowering this page builds on. - Agent runbooks — the condensed self-vs-module-local procedure.