Skip to Content
defold-typescript
Get startedGuidesAPILibraries
TypeScript

TypeScript vs Lua

A translation cheat sheet for Defold developers who already know Lua. Lua on the left, the TypeScript you write on the right. It is a map, not a tutorial: skim the tables, port your mental model, and reach for the linked pages when a detail bites.

For the runtime traps the type system cannot catch — 0 and "" being truthy, nil collapsing null and undefined, typeof not narrowing engine handles — see TypeScript gotchas. This page only flags those at cheat-sheet depth and links down.

Syntax at a glance

ConceptLuaTypeScript
Line comment-- note// note
Block comment--[[ … ]]/* … */
Bind a locallocal x = 1const x = 1 (never reassigned), let x = 1 (reassigned)
Not equala ~= ba != b or a !== b — identical Lua (see the gotchas page)
Equala == ba == b or a === b — identical Lua (see the gotchas page)
Logical and / or / notand / or / not&& / || / !
String join"a" .. b"a" + b, or a template literal `a${b}`
Length#tt.length
Block delimitersthen … end, do … end{ … }
Absencenilundefined — write it, never null (both lower to nil; see passing absence)
Index base1-based: t[1]0-based: arr[0]

Two things to internalise before the rest of the page:

  • Equality has no loose/strict split here. == / != and === / !== compile to the same non-coercing Lua == / ~=, so JavaScript's coercion — the thing === guards against — never happens in the output. The scaffolded biome.json ships noDoubleEquals off, so neither form lints; use whichever reads best — the worked examples here (such as the Tetris build) use == / != to mirror Lua's == / ~=. Both are value equality for primitives and reference equality for objects — the same split Lua draws between numbers/strings and tables. The one real equality trap is if (cell) truthiness, since 0 is truthy in Lua — see the gotchas page.
  • Indexing flips from 1 to 0. This is the single biggest porting bug. A Lua for i = 1, #t loop becomes a for (let i = 0; i < arr.length; i++) loop, and every literal index shifts down by one. Prefer for…of (below) so you never touch the index at all.

Tables vs objects, arrays, and Maps

Lua has one container — the table — used for records, arrays, and dictionaries alike. TypeScript splits that one type into three, each with its own syntax and methods. Pick the one that matches how you actually use the data:

Lua table used as…TypeScriptNotes
Record / structobject literal { x: 1, y: 2 }fixed, named string keys
Record with a computed keyobject literal { [graphics.BUFFER_TYPE_COLOR0_BIT]: params }bracketed key from an expression — Lua's [expr] = v (e.g. render.render_target option tables keyed by engine enum constants)
Sequence / listarray [1, 2, 3]0-based; arr.length, arr.push(x)
Dictionary with arbitrary keysMapnew Map(), .set(k, v), .get(k); non-string keys

Iteration translates the same way:

LuaTypeScript
for _, v in ipairs(t) dofor (const v of arr)
for k, v in pairs(t) dofor (const [k, v] of Object.entries(obj))
for k, v in pairs(map) dofor (const [k, v] of map) (or map.entries())

Do not use for…in to walk an array — TypeScriptToLua rejects it because JavaScript for…in iterates keys in an unspecified order that differs from Lua. Use for…of for values, Object.entries / Map.entries for pairs.

Under the hood TypeScriptToLua still stores arrays in 1-based Lua tables; you write 0-based TypeScript and the transpiler emits the offset. The one place the abstraction leaks is sparse arrays: setting an element to null/undefined or leaving holes can make arr.length and Lua's # disagree, so keep arrays dense.

Beyond these three, TypeScript also gives you Set, WeakMap, WeakSet, and class, and rejects a few things outright (regex, BigInt). For the full map of what is built in, what each lowers to, its lualib cost, and what to reach for when something is missing, see Data structures.

Engine indexes use Defold's base

Every position a built-in Defold API takes or returns is passed in Defold's own base, unchanged. Most count from 1, so the first fixture, cell or byte is 1. The transpiler adds nothing and subtracts nothing: the number you write is the number Defold receives, and the number Defold returns is the number you read.

declare const body: Opaque<"b2Body">;
declare const url: Url;
// the first fixture
print(b2d.fixture.get_density(body, 1));
// the bottom-left cell, fed straight back in
const [x, y] = tilemap.get_bounds(url);
tilemap.set_tile(url, "layer1", x, y, 3);

Every position the engine API takes or returns, by the base Defold counts it from:

BaseAPIPosition
⚠️ 1-basedb2d.body.destroy_fixturefixture_index
⚠️ 1-basedb2d.fixture.get_aabb, b2d.fixture.get_density, b2d.fixture.get_filter_data, b2d.fixture.get_friction, b2d.fixture.get_restitution, b2d.fixture.get_shape, b2d.fixture.get_type, b2d.fixture.is_sensor, b2d.fixture.refilter, b2d.fixture.set_density, b2d.fixture.set_filter_data, b2d.fixture.set_friction, b2d.fixture.set_restitution, b2d.fixture.set_sensor, b2d.fixture.set_shape, b2d.fixture.test_pointfixture_index
⚠️ 1-basedb2d.fixture.get_aabb, b2d.fixture.get_filter_data, b2d.fixture.set_filter_datachild_index
⚠️ 1-basedb2d.body.create_fixtureindex field of the returned fixture
⚠️ 1-basedb2d.body.get_fixturesindex field of the returned fixtures
⚠️ 1-basedb2d.world.overlap_aabb, b2d.world.overlap_shapeindex field of the returned fixtures
⚠️ 1-basedb2d.body.create_shapeindex field of the returned result
⚠️ 1-basedb2d.body.destroy_shapeshape_index
⚠️ 1-basedb2d.shape.are_contact_events_enabled, b2d.shape.are_hit_events_enabled, b2d.shape.are_pre_solve_events_enabled, b2d.shape.are_sensor_events_enabled, b2d.shape.enable_contact_events, b2d.shape.enable_hit_events, b2d.shape.enable_pre_solve_events, b2d.shape.enable_sensor_events, b2d.shape.get_body, b2d.shape.get_closest_point, b2d.shape.get_contact_capacity, b2d.shape.get_contact_data, b2d.shape.get_mass_data, b2d.shape.get_material, b2d.shape.get_sensor_capacity, b2d.shape.get_sensor_overlaps, b2d.shape.get_shape, b2d.shape.get_world, b2d.shape.is_valid, b2d.shape.ray_cast, b2d.shape.set_material, b2d.shape.set_shapeshape_index
⚠️ 1-basedbullet3d.constraint.enable_spring, bullet3d.constraint.get_6dof_angle, bullet3d.constraint.get_6dof_axis, bullet3d.constraint.get_6dof_motor, bullet3d.constraint.get_6dof_position, bullet3d.constraint.get_limit, bullet3d.constraint.is_limited, bullet3d.constraint.set_6dof_motor, bullet3d.constraint.set_limit, bullet3d.constraint.set_spring_damping, bullet3d.constraint.set_spring_equilibrium_point, bullet3d.constraint.set_spring_stiffnessaxis
⚠️ 1-basedbullet3d.collision_object.get_shapeshape_index
⚠️ 1-basedbullet3d.shape.get_indexreturned shape_index
⚠️ 1-basedbullet3d.world.cast_ray, bullet3d.world.cast_shapeshape_index field of the returned hits
⚠️ 1-basedbullet3d.world.cast_ray_closest, bullet3d.world.cast_shape_closestshape_index field of the returned hit
⚠️ 1-basedclient:sendi and j; counts from the end when negative
⚠️ 1-basedclient:sendreturned index and lastindex
⚠️ 1-basededitor.ui.open_resourceargs
⚠️ 1-basedgo.get, go.setindex field of options
⚠️ 1-basedgui.get, gui.setindex field of options
⚠️ 1-basedimage.pixelx and y
⚠️ 1-basedimage.pixelsreturned iterator
⚠️ 1-basedprofiler.view_recorded_frameframe field of frame_index
⚠️ 1-basedresource.create_atlas, resource.set_atlasframe_start and frame_end fields of table
⚠️ 1-basedresource.create_atlas, resource.set_atlasframe_start, frame_end and frames fields of table.animations
⚠️ 1-basedresource.get_atlasframes field of the returned data.animations
⚠️ 1-basedtilemap.set_tile, tilemap.get_tile, tilemap.get_tile_infox and y
⚠️ 1-basedtilemap.get_boundsreturned x and y
⚠️ 1-basedtilemap.tiles.get_infoindex field of the returned info
⚠️ 1-basedtilemap.tiles.get_tilereturned tile_index
⚠️ 1-basedtilemap.tiles.settile_or_info
⚠️ 1-basedtilemap.tiles.setindex field of tile_or_info
0️⃣ 0-basedcrash.get_user_field, crash.set_user_fieldindex
0️⃣ 0-basedgui.get_indexreturned index
0️⃣ 0-basedgui.get_layout_objectstext_offset field of the returned objects
0️⃣ 0-basedlabel.get_layout_objectstext_offset field of the returned objects
0️⃣ 0-basedon_inputgamepad field of action
0️⃣ 0-basedresource.set_texturepage and mipmap fields of table
0️⃣ 0-basedresource.create_atlas, resource.set_atlasindices field of table.geometries
0️⃣ 0-basedresource.get_atlasindices field of the returned data.geometries
  • Round trips — a value an engine call returned goes straight back in: client.send(data, lastindex + 1) resumes after the last byte sent, and b2d.fixture.get_density(body, b2d.body.get_fixtures(body)[0].index) reads the first fixture. The [0] there is an ordinary TypeScript array index; the index field it reads is Defold's.
  • Counting from the end — a negative i or j at client.send counts from the end, as in string.sub: client.send(data, 1, -1) sends the whole string.
  • Not positions — counts, ids, enum constants, the Box2D group_index collision group, array-valued tables such as model.set_blend_weights's weights, and sentinels such as the tile 0 that clears a tilemap.set_tile cell.

TypeScript arrays keep their own zero-based indexing, which TypeScriptToLua lowers as usual: arr[0] is the first element. Only the numbers an engine API takes or returns follow Defold's base.

Each classified slot's hover states its base in one bold sentence led by a marker: "⚠️ 1-based; passed to Defold unchanged.", or "0️⃣ 0-based; passed to Defold unchanged." A table field's names the field after the marker: "⚠️ index is 1-based; passed to Defold unchanged." The API reference notes each index position on a library or extension page the same way, naming the library that counts from that base: "⚠️ 1-based; passed to gooey unchanged." The same note shows in the editor hover for every library declaration, such as bridge, druid, gooey and tile_raycast, and for each extension resolve types from a curated page, such as steam and spine. resolve reads which pages are curated from library data, so a newly curated page reaches the hover with no CLI upgrade.

Because nothing is converted, an engine function behaves like any other function: you can pass it as a value, alias it, spread arguments into it, or call it through .call, .apply and .bind. A table you pass reaches Defold as the same table. Hand-written .lua files and native extension APIs see the same values TypeScript does.

Engine array properties: options.index

go.get, go.set, gui.get and gui.set take an options.index that picks one element of an array property, such as a material constant array. It is 1-based, as Defold documents, and passes through unchanged:

declare const url: Url;
// the first element: tint_array[0] in the shader
go.set(url, "tint_array", vmath.vector4(1, 0, 0, 1), { index: 1 });

{ index: i } emits {index = i}. An options variable, a spread and an index that may be undefined pass through as written. For go.get and go.set the options table names at most one of index, key and keys, since the engine raises on two.

Modules: require vs import

Lua wires files together with require and a returned table. TypeScript uses import / export, and TypeScriptToLua lowers them straight back onto Lua's module system — an import becomes a require, and your exports become the module's returned table.

LuaTypeScript
local M = {} … return Mexport function f() {}, export const C = …
local foo = require("foo")import { f, C } from "./foo"
local foo = require("foo") (whole table)import * as foo from "./foo"

Use relative specifiers ("./foo", "../lib/util") for your own files under src/1. Engine APIs are different: the namespaces go, msg, vmath, sprite, gui, render, and the rest ship from @defold-typescript/types as ambient globals, so you call vmath.vector3(…) or msg.post(…) with no import at all. You only import your own modules.

File structure and script mapping

You edit TypeScript under src/; the toolchain emits Lua beside each source by default. Files that call lifecycle factories become Defold-loadable components, and helper-only files become Lua modules for imports:

src/main.ts   →   src/main.ts.script
src/util.ts   →   src/util.lua

Defold resolves a resource by the extension after its last dot, so a .ts.script file is a valid .script component the engine loads directly — the .ts in the name only marks its TypeScript origin. src/util.lua is a plain Lua module whose path matches the require("src.util") emitted for import "./util". Run bunx @defold-typescript/cli build once or bunx @defold-typescript/cli watch to keep outputs current.

Lua scripts attach behaviour by defining bare global callbacks (function init(self), function on_input(self, action_id, action)). In TypeScript you type those through defineScript instead, which gives self and the message and input payloads real types. See script lifecycle for the full surface and the per-kind API walls.

Standard library and built-ins

This is where Lua and TypeScript diverge most, because they ship different standard libraries. TypeScriptToLua targets the ECMAScript feature set: when you write idiomatic TypeScript — array methods, string methods, Math, template literals — the transpiler emits the matching Lua via its runtime library. So the idiomatic move is to use the TypeScript form, not to call the Lua global.

LuaIdiomatic TypeScript
table.insert(t, x)arr.push(x)
#tarr.length
string.format("%d", n)template literal `${n}`
tostring(x)`${x}` or String(x)
tonumber(s)Number(s)
string.sub, string.find, …str.slice, str.indexOf, …
math.abs, math.floor, …Math.abs, Math.floor, …

A caveat worth knowing: Array.prototype.sort lowers to Lua's table.sort, which is not stable, unlike JavaScript's guaranteed-stable sort. If element order among equal keys matters, sort on a tiebreaker.

The raw Lua standard library — the math, os, string, table, and coroutine tables plus base globals like pairs, ipairs, pcall, print, tostring, type, assert, and setmetatable — is part of the ambient surface: @defold-typescript/types references the lua-types package, so these type-check and autocomplete with no import. Defold's own hash() is ambient too and returns Hash. Reach for a local declare global only for genuinely Lua/Defold-specific globals the type package does not cover.

A declare global block is type-only: it emits no Lua. The first assignment to the declared name is what creates the global at runtime, and it lowers to a bare VM-wide Lua global — no local, no module prefix. Given declare global { var FOO: number }, the use site FOO = FOO + 1 compiles to exactly FOO = FOO + 1. That global is shared across the entire VM, broader than a require-cached module local, so for ordinary app state prefer a module singleton — see Where script state lives for the full placement picture.

Two of Lua's basic types deserve a note because Defold leans on them. Userdata is arbitrary C data stored in a Lua variable — Defold uses it for hashes, URLs, the math objects (vector3, vector4, matrix4, quaternion), game objects, GUI nodes, render predicates, render targets, and constant buffers. You never name userdata in TypeScript: each one surfaces as a distinct branded type (Hash, Url, Vector3, Vector4, Matrix4, Quaternion, …) so the compiler stops you mixing a hash with a vector or a plain table. Threads are independent execution contexts and back Lua coroutines; the ambient coroutine table (from lua-types) creates and resumes them and returns a LuaThread. Coroutines work, but for frame-paced waiting prefer Defold's own timer.* / go.animate scheduling.

Prefer the idiomatic-TypeScript column above wherever it exists. The case where you must reach for the Lua global is random numbers. Defold's RNG is deterministic until seeded, and the only way to seed it is the Lua call:

math.randomseed(os.time());
const roll = math.random(1, 6); // integer in [1, 6]

Math.random() and math.random(m, n) are not interchangeable. Math.random() returns a [0, 1) float (TypeScriptToLua (TSTL) lowers it to a Lua runtime helper) and cannot be seeded; math.random(m, n) returns an integer in [m, n] from the seedable engine RNG. Use the Lua form whenever you need a reproducible or integer-ranged result.

The transpiler targets Lua 5.1 to match Defold's runtime (LuaJIT on native and desktop, a 5.1 VM on HTML5). That keeps the emitted code clear of 5.4-only constructs — integer division //, bitwise operators, goto, the two-argument math.randomseed — which the engine would reject. The ambient math.randomseed is correspondingly single-argument, so the two-argument form is a type error, not a runtime surprise.

Libraries

  • Your own code is just more TypeScript files — import them by relative path. No registration step, no manifest.
  • npm packages do not resolve at all — not even a pure, dependency-free one. The build compiles a virtual program of your include-matched files only, so node_modules is never read and the import fails loudly. Copy the source into your project and import it relatively instead; see npm packages do not resolve.
  • Engine features come from the ambient @defold-typescript/types namespaces (go, msg, vmath, …), never from npm. There is no package to install for them; they are part of the types surface the scaffold pins.

See also

  • TypeScript gotchas — the runtime sharp edges this page only points at: truthiness, nil collapse, typeof, opaque handles.
  • Script lifecycle — typing self, on_message, and on_input with defineScript.
  • Where script state lives — per-instance self, shared module locals, module singletons, and the VM-global declare global lowering.
  • Data structures — the full container availability map: Array, tuple, Map, Set, WeakMap, WeakSet, object record, and class, plus what is not available and what to use instead.
  • Vector math — why v3 + v3 is not allowed and you use v3.add(other) instead.
  • Getting started — scaffold, write a script, build to Lua.

Footnotes

  1. src/ is this guide's shorthand and the scaffold's default, not a fixed location. Your source roots are the include globs in tsconfig.json — ["src/**/*.ts"] out of the box, and any list of folders you set; build and watch compile exactly what those globs match, and ignore exclude. ↩

On this page