Skip to contentGo to cookie choices
Skip to docs navigation
Engines

Defold

Use ZokoGames from Defold HTML5 builds with the zokogames Lua library and its small native extension.

About 14 minutes

https://docs.zokogames.com/engines/defold

The zokogames library (packages/sdk-engines/defold) is a Lua API plus a small native extension (zokogames/ext.manifest, zokogames/src/zokogames_ext.cpp and zokogames/lib/web/lib_zokogames.js, compiled by Defold's build server when you bundle). It evaluates a JavaScript bridge with html5.run() and loads the ZokoGames SDK script for you. With the extension built in, the browser SDK pushes results straight into Lua (zokogames.is_native is true); if the extension is not part of your bundle, the module polls the bridge every 50 ms instead. Outside HTML5 (the editor, desktop builds) a Lua simulator answers. Terms such as "midgame" and "rewarded" are in the glossary.

Note

Status (1.7.0): built for the web with Defold's official build tool, bob 1.14.1, with the native extension built by Defold's build server; the library resolved as a dependency and the bundle ran every call in a real browser (2026-11-23). Other Defold versions were not tried. Send the Defold version and the exact error or build-server log to support if the first import fails.

Install#

Download the Defold plugin: /sdk-engines/zokogames-defold-1.7.0.zip (the same files as the folder in the repository).

/sdk-engines/defold.zip is always the latest version. Checksums: /sdk-engines/SHA256SUMS. Index of every engine package with its version, size and SHA-256: /sdk-engines/engines.json.

  1. Add the library to your project. It is a Defold library project (game.project has [library] include_dirs = zokogames). Either copy the zokogames folder into your project, or host the archive and add it as a dependency, then run Project > Fetch Libraries:
INI
[project]
dependencies#0 = <URL of your zokogames library archive>
  1. Require the module and call init once from a script's init function:
Lua
local zoko = require "zokogames.zokogames"
  1. Bundle for HTML5 with native extensions enabled (the default). The module injects https://sdk.zokogames.com/zokogames-sdk-v1.js itself on the first init, so no HTML change is needed to run. But the upload validator reads your files statically, and the injected URL lives inside the bridge code, so it can raise no_sdk ("the SDK script is not referenced"), and a build without the SDK cannot go to full launch (see build validation). To be safe, use a custom HTML5 template: copy Defold's default /builtins/manifests/web/engine_template.html into your project, point the .html Shell setting at it (htmlfile in the [html5] section of game.project) and add <script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script> to its <head>; the module then finds the SDK already loaded.

The module also ships bridge_js.lua (the embedded bridge source, regenerated with tools/embed-defold-bridge.mjs after editing zokogames/web/zokogames_bridge.js) and examples/store.script.

Which path#

You are Do this
A Defold hobbyist with a finished game Copy the folder, add the script below to a bootstrap object, bundle HTML5, upload.
Cautious about native extensions Bundle without them; the module falls back to polling (up to 50 ms latency).

A working script#

Attach this to a game object in your bootstrap collection. It covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

Lua
local zoko = require "zokogames.zokogames"

local function set_paused(p)
	msg.post("@system:", "set_time_step", { factor = p and 0 or 1, mode = 0 })   -- sound: zoko.mute_audio_during_ads
end

function init(self)
	self.in_ad = false
	zoko.init(function(err)
		if err then print("ZokoGames:", err.code) end         -- the game must still run
		if zoko.is_available() then                          -- initialised and not "disabled"
			set_paused(false)                                -- portal mute: zoko.follow_portal_mute
			self.best = tonumber(zoko.data.get_item("best")) or 0   -- load: synchronous, nil when missing
			zoko.game.loading_stop()                         -- ends the portal's loading bar: the game can be played now
		end
		msg.post("#", "start_game")
	end)
end

-- Ads: pause on started, resume on finished AND error. Never pause before `started`.
local function show_ad(self, ad_type, on_reward)
	if not zoko.is_available() then return end
	local function resume()
		if not self.in_ad then return end
		self.in_ad = false
		set_paused(false)
	end
	zoko.ad.request_ad(ad_type, {
		started = function() self.in_ad = true; set_paused(true) end,
		finished = function() resume(); if on_reward then on_reward() end end,   -- reward only here
		error = function(e) resume(); print("no ad:", e.code) end,              -- adCooldown, unfilled, adblock ...
	})
end

function on_message(self, message_id, message, sender)
	if message_id == hash("start_game") then
		if zoko.is_available() then zoko.game.gameplay_start() end             -- player has control
	elseif message_id == hash("round_over") then
		if zoko.is_available() then zoko.game.gameplay_stop() end
		local score = message.score
		if score > (self.best or 0) then
			self.best = score
			local ok, e = zoko.data.set_item("best", score)                   -- numbers are converted to strings
			if not ok then print(e.code) end                                   -- for example dataLimitExceeded
		end
		zoko.user.get_user(function(err, user)
			-- "" works only on a board WITHOUT an encryption key; see the leaderboards page.
			if not err and user then zoko.user.submit_score("", score) end
		end)
		show_ad(self, "midgame")                                               -- natural break
	elseif message_id == hash("reward_button") then
		show_ad(self, "rewarded", function() print("reward granted") end)
	end
end

The wrapper handles sound: it sets the gain of the "master" sound group to 0 while an ad plays (zoko.mute_audio_during_ads) and while the portal asks for mute (zoko.follow_portal_mute), and restores your gain afterwards. Both are true by default; set one to false to handle that part yourself. Pausing the game (set_time_step above) stays your job.

About the leaderboard: a board with an encryption key counts only a correctly encrypted payload (leaderboards), and the library has no encryption helper, so "" works only on a board without a key. Otherwise compute scores on your server and use the server API. The player id for encryption is the __dangerousUserId field of the user table.

How calls work#

Names are snake_case. Calls that wait for the browser take an optional callback as the last argument with the shape callback(err, result). err is nil on success and a table { code, message } otherwise (zoko.is_error(err, "purchaseCancelled") tests a code).

State is available as plain fields once init has finished: zoko.environment ("local", "zokogames" or "disabled"), is_initialized, is_simulated, is_native, is_qa_tool, is_user_account_available, is_store_available, is_instant_multiplayer, is_offline, system_info, invite_params and settings. zoko.is_available() is true when initialised and not disabled.

JavaScript Lua
SDK.init() zoko.init(callback)
SDK.ad.requestAd(type, cbs) zoko.ad.request_ad("midgame", { started = f, finished = f, error = f })
SDK.ad.hasAdblock() zoko.ad.has_adblock(callback)
SDK.banner.requestBanner(...) zoko.banner.request_banner(id, width, height, rect, callback)
SDK.banner.requestResponsiveBanner(id) zoko.banner.request_responsive_banner(id, rect, callback)
clearBanner, clearAllBanners zoko.banner.clear_banner(id, callback), zoko.banner.clear_all_banners(callback)
SDK.game.gameplayStart() and friends zoko.game.gameplay_start(), gameplay_stop, loading_start, loading_stop, happytime, left_room
loadingProgress(n) zoko.game.loading_progress(n, callback)
reportGameCompletedPercentage(n) zoko.game.report_game_completed_percentage(n, callback)
setGameContext(obj), clearGameContext() zoko.game.set_game_context(table, callback), clear_game_context
updateRoom(u), inviteLink(p) zoko.game.update_room(table, callback), zoko.game.invite_link(table, callback)
showInviteButton(p), hideInviteButton() (deprecated) zoko.game.show_invite_button(table, callback), zoko.game.hide_invite_button(callback); use update_room instead
isInstantMultiplayer zoko.game.is_instant_multiplayer() (alias is_instant_join()), field zoko.is_instant_multiplayer
SDK.game.settings zoko.game.get_settings(), add_settings_change_listener(fn), remove_settings_change_listener(fn)
isOffline, offline listeners zoko.game.is_offline(), add_offline_listener(fn) (gets the new boolean), remove_offline_listener(fn)
join room listeners zoko.game.add_join_room_listener(fn), remove_join_room_listener(fn)
getInviteParam(k) zoko.game.get_invite_param(key) (synchronous)
SDK.user.getUser() zoko.user.get_user(callback)
SDK.user.isUserAccountAvailable, systemInfo zoko.user.is_user_account_available(), zoko.user.get_system_info()
listFriends(opts) zoko.user.list_friends(page, size, callback)
getUserToken(opts) zoko.user.get_user_token(signing_key_type, callback) (pass nil for the default)
showAuthPrompt(), showAccountLinkPrompt() zoko.user.show_auth_prompt(callback), show_account_link_prompt(callback); listeners add_auth_listener(fn), remove_auth_listener(fn)
submitScore(opts) zoko.user.submit_score(encrypted_score, score, callback)
SDK.data.* zoko.data.get_item(key) (nil when missing), has_key, set_item(key, value) (returns true, or false and an error table), remove_item, clear
SDK.store.* zoko.store.is_available(), get_catalog_items({ limit = 20 }, cb), get_player_inventory(options, cb), buy_item(sku, cb), consume_item(sku, qty, cb), get_purchase_token(cb), set_sandbox(bool)
SDK.achievements.list() / unlock(key) / onUnlock zoko.achievements.list(callback), zoko.achievements.unlock(key, callback), zoko.achievements.on_unlock(fn), zoko.achievements.remove_unlock_listener(fn); see achievements
SDK.analytics.trackOrder(p, o) zoko.analytics.track_order(provider, order, callback)
SDK.analytics.track(name, params) (1.7.0) zoko.analytics.track(name, params) (no callback)

zoko.VERSION is the JavaScript SDK release the library was written against. The published plugin (1.7.0) reports "1.7.0". Plugin versions are separate from the SDK version, and the plugins are repacked at the next plugin release. zoko.SDK_SCRIPT_URL is the script it loads. The deprecated zoko.user.get_xsolla_user_token(callback) is an alias of zoko.store.get_purchase_token. Error codes are in zoko.ERROR_CODES (a table keyed by module, for example zoko.ERROR_CODES.store).

Kids mode. Since version 1.5.0 the wrapper exposes it: zoko.settings.kidsMode is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring disableChat, which the portal sets to true in the same cases. To test it, switch on zoko.sim.kids_mode in the simulator (it also turns chat off, as the portal does). See kids mode.

Room data channel#

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after updateRoom (or after joining from an invite) and ends with leftRoom, needs a signed-in player and a portal with realtime enabled (otherwise roomUnavailable), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of A-Z a-z 0-9 _ . : -. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (notInRoom, notHost, payloadTooLarge, stateTooLarge, unknownMember, rateLimited, roomUnavailable) are in the game module and the multiplayer guide.

zoko.game.room carries it (also zoko.room). Payloads are JSON: tables, strings, numbers and booleans. Lua tables cannot hold nil, so use remove_state to delete a state key. Listen with room.set_listener(self, fn), which calls fn(self, event, data) with event one of "message", "state", "members", "host_changed" or "error", or with the per-event add_*_listener functions. The native extension and the polling fallback share the same bridge, so there is nothing extra to build. Outside HTML5 the simulator is one room with one member that receives its own messages and state changes.

JavaScript Lua
room.send(data, { to }) zoko.game.room.send(data, callback), send_to(member_id, data, callback)
room.onMessage(cb) event "message" (data = { from, data, direct, seq, ts }) or add_message_listener(fn) / remove_message_listener(fn)
room.setState(patch) set_state(patch, callback), remove_state(keys, callback)
room.getState(), room.onState(cb) get_state(); event "state" ({ state, change }) or add_state_listener(fn) / remove_state_listener(fn)
room.members(), room.onMembers(cb) members(); event "members" or add_members_listener(fn) / remove_members_listener(fn)
room.isHost(), room.onHostChange(cb), room.selfId is_host(); event "host_changed" ({ host_id, is_host }); self_id(); add_host_change_listener(fn) / remove_host_change_listener(fn)
room.addLeftListener(cb) (1.7.0) event "left" ({ reason, room_id }) or add_left_listener(fn) / remove_left_listener(fn)
room.onError(cb) event "error" or add_error_listener(fn) / remove_error_listener(fn)
Lua
function init(self)
	zoko.init(function(err)
		if err then return end
		zoko.game.room.set_listener(self, function(self, event, data)
			if event == "message" then print(data.from, data.data.cell)
			elseif event == "host_changed" and data.is_host then zoko.game.room.set_state({ turn = "X" }) end
		end)
		zoko.game.update_room({ roomId = "match-1", isJoinable = true })
	end)
end

function on_input(self, action_id, action)
	if action.pressed then zoko.game.room.send({ cell = 4, mark = "X" }) end
end

Banners#

Banners are DOM elements drawn over the canvas. Describe where one should sit with a rectangle { x, y, w, h } in window pixels with the origin at the top left (optional area_w and area_h name the window size the numbers refer to), or build one from a GUI node (centred pivot assumed). Request banners on menu screens only.

Lua
local rect = zoko.banner.rect_from_gui_node(gui.get_node("banner_slot"))
zoko.banner.request_responsive_banner("menu", rect, function(err)
	if err then print("banner:", err.code) end
end)

Purchases#

Lua
if zoko.store.is_available() then
	zoko.store.get_catalog_items({ limit = 20 }, function(err, items)
		if err or #items == 0 then return end
		zoko.store.buy_item(items[1].sku, function(e, paid)
			if zoko.is_error(e, "purchaseCancelled") then return end
			if e then print(e.code) return end
			zoko.store.get_purchase_token(function(_, token) print(token) end)   -- send to your server and verify there
		end)
	end)
end

Verify ownership on your server (in-game purchases). examples/store.script is the full flow.

HTML5 export settings that matter#

  • Bundle > HTML5: architecture wasm-web. Add js-web only if you must support very old browsers (it roughly doubles the size). Do not choose a threaded variant: threads need SharedArrayBuffer, which needs cross-origin isolation headers, and the portal sends none. Release, not Debug.
  • No renaming, no pre-compression. Keep the engine's .wasm unmodified and do not rename files to .br or .gz: the loader requests plain names. The game origin serves a .br or .gz suffix with the matching Content-Encoding, but only by file name, so it helps engines that request those names (Unity). The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
  • Size. Use texture profiles (Basis or ASTC for web), remove unused engine components in game.project, and use collection proxies with excluded resources or live update to load later levels.
  • Canvas sizing. The frame size changes with fullscreen and rotation. Choose a scale mode in the HTML5 section of game.project that keeps your aspect ratio, so the game fits every required resolution.
  • Memory. The HTML5 heap is fixed by game settings; keep it modest for mobile browsers and unload collections you no longer need.
  • Audio unlock. Browsers keep audio suspended until the first click or tap. Start music from a "tap to play" screen, not in init.
  • Fullscreen. Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so Defold's own fullscreen request works from an input event, but it fullscreens only your canvas; do not add a competing button.
  • Loading. Call zoko.game.loading_start() when your loading collection starts, loading_progress(p) as proxies load, and loading_stop() when the player can act.

Upload: Project > Bundle > HTML5, zip the bundle folder contents so index.html is at the archive root, upload it in the developer console, and run the Preview tool first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

Chat reports, screenshots and storage mirror#

Since SDK 1.4.0: zoko.game.report_chat(report, callback), zoko.game.set_screenshot_provider(fn) and zoko.data.mirror_local_storage({ prefix = "save_" }). The canvas is only readable right after drawing, so call zoko.game.screenshot_tick() at the end of your render script (a 1.5 second timer answers if you do not). sys.save files live in IndexedDB, not localStorage, so the mirror does not see them; use zoko.data.set_item. The Lua simulator accepts all three.

Ad rules#

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (zoko.ad.request_ad("midgame", ...)); the only other type is rewarded. In local mode (testing on localhost, outside the portal) a midgame request fails with the error callback with adCooldown until your game has called zoko.game.gameplay_start() or 30 seconds of visible page time have passed. On the portal the first midgame ad needs zoko.game.gameplay_start() first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: ads reference and ads guide.

Test locally#

  • Outside HTML5 (the editor, desktop bundles) zoko.is_simulated is true and the Lua simulator answers. Edit fields of zoko.sim before init: disabled, account_available, logged_in, username, user_id, friend_count, ad_behaviour ("fill", "no_fill" or "error"), ad_duration (seconds, default 1.5), adblock, mute_audio, offline, disable_chat, store_available, verbose. Cloud save is kept with sys.save; the simulated store has three items and an in-memory inventory.
  • Difference to remember. The simulator does not enforce the three-minute midgame cooldown (adCooldown) that the portal and the browser's local mode do.
  • An HTML5 bundle on localhost uses the JavaScript SDK's own local mode: a three-second ad overlay, fake players, localStorage saves, ?sdk_debug=true, ?ad_response=unfilled. Serve the bundle from a local web server; on another host the environment is disabled unless you add ?useLocalSdk=true.
  • Then open the Preview tool with your local address and watch the checklist tick.

Known pitfalls#

  • zoko.is_native is false in the browser. The bundle was made without native extensions. The polling fallback still works, with up to 50 ms latency.
  • module 'zokogames.bridge_js' not found. Copy the whole zokogames/ folder; regenerate the file with node tools/embed-defold-bridge.mjs after editing the bridge.
  • Callbacks never fire. Call zoko.init first and keep the objects that own the callbacks alive (a script whose game object was deleted will not receive them).
  • Build server error in zokogames_ext.cpp. Report the Defold version and the full log; or bundle without native extensions.
  • sdkNotLoaded. The browser could not load the SDK script (offline or blocked).
  • Game stays paused after an ad. Resume in error as well as finished. A request that cannot start at all (SDK disabled) calls only error, never started.

Next#