Heroic Labs Documentation

Function Reference #

The code runtime built into the server includes a module with functions to implement various logic and custom behavior, enabling you to define authoritative code and conditions on input received by clients. Learn more about it in the Server Framework Basics documentation.

This page lists all functions available within Nakama and their respective parameters, with corresponding code samples for each. If you haven’t already, see the documentation on using the server framework.

Writing custom SQL is discouraged in favor of using the built-in features of the Storage Engine. If custom SQL is needed for your use case, please contact Heroic Labs before proceeding.
The creation of custom tables is strongly discouraged.

Accounts #

account_delete_id #

Delete an account by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID for the account to be deleted. Must be valid UUID.
recorded boolfalseWhether to record this deletion in the database. By default this is set to false.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
nk.account_delete_id("8f4d52c7-bf28-4fcf-8af2-1d4fcf685592", false)

account_export_id #

Export account information for a specified user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID for the account to be exported. Must be valid UUID.
Returns
NameDescription
export stringAccount information for the provided user ID, in JSON format.
error errorAn optional error value if an error occurred.
1
2
local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local account_data = nk.account_export_id(user_id)

account_get_id #

Fetch account information by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to fetch information for. Must be valid UUID.
Returns
NameDescription
account tableAll account information including wallet, device IDs and more.
error errorAn optional error value if an error occurred.
1
2
3
local account = nk.account_get_id("8f4d52c7-bf28-4fcf-8af2-1d4fcf685592")
local wallet = account.wallet
nk.logger_info(string.format("Wallet is: %s", nk.json_encode(wallet)))

accounts_get_id #

Fetch information for multiple accounts by user IDs.

Parameters
NameDefaultDescription
userIds table REQUIREDTable of user IDs to fetch information for. Must be valid UUID.
Returns
NameDescription
account TableTable of accounts.
error errorAn optional error value if an error occurred.
1
2
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local accounts = nk.accounts_get_id(user_ids)

account_update_id #

Update an account by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID for which the information is to be updated. Must be valid UUID.
metadata tableThe metadata to update for this account.
username stringUsername to be set. Must be unique. Use null if it is not being updated.
displayName stringDisplay name to be updated. Use null if it is not being updated.
timezone stringTimezone to be updated. Use null if it is not being updated.
location stringLocation to be updated. Use null if it is not being updated.
language stringLang tag to be updated. Use null if it is not being updated.
avatarUrl stringUser's avatar URL. Use null if it is not being updated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521" -- Some user ID.
local metadata = {}
local username = ""
local display_name = nil
local timezone = nil
local location = nil
local language = nil
local avatar_url = nil
nk.account_update_id(user_id, metadata, username, display_name, timezone, location, language, avatar_url)

Authenticate #

authenticate_apple #

Authenticate user and create a session token using an Apple sign in token.

Parameters
NameDefaultDescription
token string REQUIREDApple sign in token.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_apple("some-oauth-access-token", "username", true)

authenticate_custom #

Authenticate user and create a session token using a custom authentication managed by an external service or source not already supported by Nakama.

Parameters
NameDefaultDescription
id string REQUIREDCustom ID to use to authenticate the user. Must be between 6-128 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_custom("48656C6C6F20776F726C64", "username", true)

authenticate_device #

Authenticate user and create a session token using a device identifier.

Parameters
NameDefaultDescription
id string REQUIREDDevice ID to use to authenticate the user. Must be between 1-128 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_device("48656C6C6F20776F726C64", "username", true)

authenticate_email #

Authenticate user and create a session token using an email address and password.

Parameters
NameDefaultDescription
email string REQUIREDEmail address to use to authenticate the user. Must be between 10-255 characters.
password string REQUIREDPassword to set. Must be longer than 8 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_email("email@example.com", "48656C6C6F20776F726C64", "username", true)

authenticate_facebook #

Authenticate user and create a session token using a Facebook account token.

Parameters
NameDefaultDescription
token string REQUIREDFacebook OAuth or Limited Login (JWT) access token.
import booltrueWhether to automatically import Facebook friends after authentication.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_facebook("some-oauth-access-token", true, "username", true)

authenticate_facebook_instance_game #

Authenticate user and create a session token using a Facebook Instant Game.

Parameters
NameDefaultDescription
playerInfo string REQUIREDFacebook Player info.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_facebook_instant_game("player-info", true, "username", true)

authenticate_game_center #

Authenticate user and create a session token using Apple Game Center credentials.

Parameters
NameDefaultDescription
playerId string REQUIREDPlayerId provided by GameCenter.
bundleId string REQUIREDBundleId of your app on iTunesConnect.
timestamp number REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_game_center(player_id, bundle_id, timestamp, salt, signature, public_key_url, username, create)

authenticate_google #

Authenticate user and create a session token using a Google ID token.

Parameters
NameDefaultDescription
token string REQUIREDGoogle OAuth access token.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_google("some-id-token", "username", true)

authenticate_steam #

Authenticate user and create a session token using a Steam account token.

Parameters
NameDefaultDescription
token string REQUIREDSteam token.
username stringThe user's username. If left empty, one is generated.
import booltrueWhether to automatically import Steam friends after authentication.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
created boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
local user_id, username, created = nk.authenticate_steam("steam-token", "username", true)

authenticate_token_generate #

Generate a Nakama session token from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to use to generate the token.
username stringThe user's username. If left empty, one is generated.
expiresAt numberUTC time in seconds when the token must expire. Defaults to server configured expiry time.
Returns
NameDescription
token stringThe Nakama session token.
validity numberThe period for which the token remains valid.
error errorAn optional error value if an error occurred.
1
2
local token, exp = nk.authenticate_token_generate("user_id", "username")
nk.logger_info(("Access token: %q, valid for %q seconds"):format(token, exp))

Link Apple authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
token string REQUIREDApple sign in token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_apple(user_id, "some-oauth-access-token")

Link custom authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
customId string REQUIREDCustom ID to be linked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_custom(user_id, "48656C6C6F20776F726C64")

Link device authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
deviceId string REQUIREDDevice ID to be linked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_device(user_id, "22226C6C6F20776F726C22")

Link email authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
email string REQUIREDAuthentication email to be linked to the user.
password string REQUIREDPassword to set. Must be longer than 8 characters.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_email(user_id, "email@example.com", "password")

Link Facebook authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
username stringIf left empty, one is generated.
token string REQUIREDFacebook OAuth or Limited Login (JWT) access token.
importFriends booltrueWhether to automatically import Facebook friends after authentication.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local import_friends = true
nk.link_facebook(user_id, "username", "some-oauth-access-token", import_friends)

Link Facebook Instant Game authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
playerInfo string REQUIREDFacebook player info.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local import_friends = true
nk.link_facebook_instant_game(user_id, "player-info", import_friends)

Link Apple Game Center authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
playerId string REQUIREDPlayer ID provided by Game Center.
bundleId string REQUIREDBundle ID of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local timestamp = 1
nk.link_gamecenter(user_id, "player_id", "bundle_id", timestamp, "salt", "signature", "public_key_url")

Link Google authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
token string REQUIREDGoogle OAuth access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_google(user_id, "some-oauth_access_token")

Link Steam authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
username string REQUIREDIf left empty, one is generated.
token string REQUIREDSteam access token.
importFriends bool REQUIREDtrueWhether to automatically import Steam friends after authentication.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local import_friends = true
nk.link_steam(user_id, "username", "some-oauth_access_token", import_friends)

Unlink Apple authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDApple sign in token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_apple(user_id, "some-oauth-access-token")

Unlink custom authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
customId string REQUIREDCustom ID to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_custom(user_id, "48656C6C6F20776F726C64")

Unlink device authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
deviceId string REQUIREDDevice ID to be unlinked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_device(user_id, "22226C6C6F20776F726C22")

Unlink email authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
email string REQUIREDEmail to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_email(user_id, "email@example.com")

Unlink Facebook authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDFacebook OAuth or Limited Login (JWT) access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_facebook(user_id, "username", "some-oauth-access-token")

Unlink Facebook Instant Game authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
playerInfo string REQUIREDFacebook player info.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_facebook_instant_game(user_id, "player-info")

Unlink Apple Game Center authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
playerId string REQUIREDPlayer ID provided by Game Center.
bundleId string REQUIREDBundle ID of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local timestamp = 1
nk.unlink_gamecenter(user_id, "player_id", "bundle_id", timestamp, "salt", "signature", "public_key_url")

Unlink Google authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDGoogle OAuth access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_google(user_id, "some-oauth_access_token")

Unlink Steam authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDSteam access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_steam(user_id, "some-oauth_access_token")

Chat #

channel_id_build #

Create a channel identifier to be used in other runtime calls. Does not create a channel.

Parameters
NameDefaultDescription
senderId string REQUIREDUserID of the message sender (when applicable). An empty string defaults to the system user.
target string REQUIREDCan be the room name, group identifier, or another username.
chanType int REQUIREDThe type of channel, either Room (1), Direct (2), or Group (3).
Returns
NameDescription
channelId stringThe generated ID representing a channel.
error errorAn optional error value if an error occurred.
1
2
3
4
local sender_id = "SenderId"
local target = "RoomName"
local channel_type = 1
local channel_id = nk.channel_id_build(sender_id, target, channel_type)

channel_message_send #

Send a message on a realtime chat channel.

Parameters
NameDefaultDescription
channelId string REQUIREDThe ID of the channel to send the message on.
content table REQUIREDMessage content.
senderId stringThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername stringThe username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persist booltrueWhether to record this message in the channel history.
Returns
NameDescription
ack tableMessage sent ack.
error errorAn optional error value if an error occurred.
1
2
3
4
5
local content = {}
content["message"] = "hello"

local create_ack = nk.channel_message_send("<ChannelId>", content, "<SenderId>", "<SenderUsername>", true)
nk.logger_info("%q created at %q", create_ack.message_id, create_ack.create_time)

channel_messages_list #

List messages from a realtime chat channel.

Parameters
NameDefaultDescription
channelId string REQUIREDThe ID of the channel to send the message on.
limit number100The number of messages to return per page.
forward booltrueWhether to list messages from oldest to newest, or newest to oldest.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
messages tableMessages from the specified channel.
nextCursor stringCursor for the next page of messages, if any. Will be set to "" or nil when fetching last available page.
prevCursor stringCursor for the previous page of messages, if any.
error errorAn optional error value if an error occurred.
1
2
local channel_id = "<ChannelId>"
local messages = nk.channel_messages_list(channel_id)

channel_message_update #

Update a message on a realtime chat channel.

Parameters
NameDefaultDescription
channelId string REQUIREDThe ID of the channel to send the message on.
messageId string REQUIREDThe ID of the message to update.
content table REQUIREDMessage content. Must be set.
senderId stringThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername stringThe username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persist booltrueWhether to record this message in the channel history.
Returns
NameDescription
ack tableMessage updated ack.
error errorAn optional error value if an error occurred.
1
2
3
4
5
local content = {}
content["message"] = "hello"

local update_ack = nk.channel_message_update("<ChannelId>", "<MessageId>", content, "<SenderId>", "<SenderUsername>", true)
nk.logger_info("%q created at %q", update_ack.message_id, update_ack.create_time)

Events #

event #

Generate an event.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the event to be created.
properties table REQUIREDA table of event properties.
timestamp int REQUIREDNumeric UTC value of when event is created.
external boolfalseWhether the event is external.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local properties = { some = "property" }
local timestamp = 0
local external = false

nk.event(name, properties, timestamp, external)

Friends #

friends_add #

Add friends to a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to whom you want to add friends.
username string REQUIREDThe name of the user to whom you want to add friends.
ids table REQUIREDThe IDs of the users you want to add as friends.
usernames table REQUIREDThe usernames of the users you want to add as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local username = "username"
local ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local usernames = {"newfriend1", "newfriend2"}

local friends = nk.friends_add(user_id, username, ids, usernames)

friends_block #

Block friends for a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user for whom you want to block friends.
username string REQUIREDThe name of the user for whom you want to block friends.
ids table REQUIREDThe IDs of the users you want to block as friends.
usernames table REQUIREDThe usernames of the users you want to block as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local username = "username"
local ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local usernames = {"blockedfriend1", "blockedfriend2"}

local friends = nk.friends_block(user_id, username, ids, usernames)

friends_delete #

Delete friends from a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user from whom you want to delete friends.
username string REQUIREDThe name of the user from whom you want to delete friends.
ids table REQUIREDThe IDs of the users you want to delete as friends.
usernames table REQUIREDThe usernames of the users you want to delete as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local username = "username"
local ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local usernames = {"exfriend1", "exfriend2"}

local friends = nk.friends_delete(user_id, username, ids, usernames)

friends_list #

List all friends, invites, invited, and blocked which belong to a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user whose friends, invites, invited, and blocked you want to list.
limit numberThe number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
state numberThe state of the friendship with the user. If unspecified this returns friends in all states for the user.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
friends tableThe user information for users that are friends of the current user.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local limit = 100
local state = nil
local cursor = nil

local friends = nk.friends_list(user_id, limit, state, cursor)

for _, m in ipairs(friends) do
  -- States are: friend(0), invite_sent(1), invite_received(2), blocked(3)
  local msg = string.format("Friend username %q has state %q", m.user.username, m.state)
  nk.logger_info(msg)
end

Groups #

group_create #

Setup a group with various configuration settings. The group will be created if they don't exist or fail if the group name is taken.

Parameters
NameDefaultDescription
userId string REQUIREDMandatory. The user ID to be associated as the group superadmin.
name string REQUIREDMandatory. Group name, must be unique.
creatorId stringThe user ID to be associated as creator. If not set or nil/null, system user will be set.
langTag stringGroup language.
description stringGroup description, can be left empty as nil/null.
avatarUrl stringURL to the group avatar, can be left empty as nil/null.
open boolfalseWhether the group is for anyone to join, or members will need to send invitations to join.
metadata tableCustom information to store for this group. Can be left empty as nil/null.
maxCount number100Maximum number of members to have in the group.
Returns
NameDescription
createGroup stringThe ID of the newly created group.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
local metadata = { -- Add whatever custom fields you want.
  my_custom_field = "some value"
}

local user_id = "dcb891ea-a311-4681-9213-6741351c9994"
local creator_id = "dcb891ea-a311-4681-9213-6741351c9994"
local name = "Some unique group name"
local description = "My awesome group."
local lang = "en"
local open = true
local creator_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local avatar_url = "url://somelink"
local maxMemberCount = 100

nk.group_create(user_id, name, creator_id, lang, description, avatar_url, open, metadata, maxMemberCount)

group_delete #

Delete a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local group_id = "f00fa79a-750f-11e7-8626-0fb79f45ff97"
nk.group_delete(group_id)

groups_get_id #

Fetch one or more groups by their ID.

Parameters
NameDefaultDescription
groupIds table REQUIREDA list of strings of the IDs for the groups to get.
Returns
NameDescription
getGroups tableA table of groups with their fields.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local group_ids = {
  "0BF154F1-F7D1-4AAA-A060-5FFED3CDB982",
  "997C0D18-0B25-4AEC-8331-9255BD36665D"
}

local groups = nk.groups_get_id(group_ids)

for _, g in ipairs(groups) do
  local msg = string.format("Group name %q with id %q", g.name, g.id)
  nk.logger_info(msg)
end

groups_list #

Find groups based on the entered criteria.

Parameters
NameDefaultDescription
name string REQUIREDSearch for groups that contain this value in their name.
langTag stringFilter based upon the entered language tag.
members number REQUIREDSearch by number of group members.
open bool REQUIREDFilter based on whether groups are Open or Closed.
limit number100Return only the required number of groups denoted by this limit value.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local group_name = "Heroic"
local lang_tag = "en"
local members = 10
local open = true
local limit = 100

local groups = nk.groups_list(group_name, lang_tag, members, open, limit)

for i, group in ipairs(groups) do
  nk.logger_info(string.format("ID: %q - can enter? %q", group.id, group.can_enter))
end

group_update #

Update a group with various configuration settings. The group which is updated can change some or all of its fields.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to update.
userId stringUser ID calling the update operation for permission checking. Set as nil to enact the changes as the system user.
name stringGroup name, can be empty if not changed.
creatorId stringThe user ID to be associated as creator. Can be empty if not changed.
langTag stringGroup language. Empty if not updated.
description stringGroup description, can be left empty if not updated.
avatarUrl stringURL to the group avatar, can be left empty if not updated.
open boolWhether the group is for anyone to join or not.
metadata tableCustom information to store for this group. Use nil if field is not being updated.
maxCount numberMaximum number of members to have in the group. Use 0, nil/null if field is not being updated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
local metadata = {
  some_field = "some value"
}

group_id = "f00fa79a-750f-11e7-8626-0fb79f45ff97"
description = "An updated description."

nk.group_update(group_id, nil, "", "", "", description, "", nil, metadata, 0)

group_user_join #

Join a group for a particular user.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to join.
userId string REQUIREDThe user ID to add to this group.
username string REQUIREDThe username of the user to add to this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local username = "myusername"

nk.group_user_join(group_id, user_id, username)

group_user_leave #

Leave a group for a particular user.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to leave.
userId string REQUIREDThe user ID to remove from this group.
username string REQUIREDThe username of the user to remove from this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local username = "myusername"

nk.group_user_leave(group_id, user_id, username)

group_users_add #

Add users to a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to add users to.
userIds table REQUIREDTable of user IDs to add to this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}

nk.group_users_add(group_id, user_ids)

group_users_ban #

Ban users from a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to ban users from.
userIds table REQUIREDTable of user IDs to ban from this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}

nk.group_users_ban(group_id, user_ids)

group_users_demote #

Demote users in a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group whose members are being demoted.
userIds table REQUIREDTable of user IDs to demote.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}

nk.group_users_demote(group_id, user_ids)

group_users_kick #

Kick users from a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to kick users from.
userIds table REQUIREDTable of user IDs to kick.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}

nk.group_users_kick(group_id, user_ids)

group_users_list #

List all members, admins and superadmins which belong to a group. This also list incoming join requests.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to list members for.
Returns
NameDescription
groupUsers tableThe user information for members, admins and superadmins for the group. Also users who sent a join request.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local members = nk.group_users_list(group_id)

for _, m in ipairs(members) do
  local msg = string.format("Member username %q has state %q", m.user.username, m.state)
  nk.logger_info(msg)
end

group_users_promote #

Promote users in a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group whose members are being promoted.
userIds table REQUIREDTable of user IDs to promote.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}

nk.group_users_promote(group_id, user_ids)

user_groups_list #

List all groups which a user belongs to and whether they've been accepted or if it's an invite.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to list groups for.
Returns
NameDescription
userGroups tableA table of groups with their fields.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local user_id = "64ef6cb0-7512-11e7-9e52-d7789d80b70b"
local groups = nk.user_groups_list(user_id)

for _, g in ipairs(groups) do
  local msg = string.format("User has state %q in group %q", g.state, g.name)
  nk.logger_info(msg)
end

Hooks #

register_leaderboard_reset #

Registers a function to be run when a leaderboard resets.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each leaderboard reset.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local function my_func(ctx, leaderboard, reset)
  -- Custom logic
end

nk.register_leaderboard_reset(my_func)

register_matchmaker_matched #

Registers a function that will be called when matchmaking finds opponents.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each matchmake completion.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
local function matchmaker_matched(context, matched_users)
  for _, m in ipairs(matched_users) do
    nk.logger_info(m.presence["user_id"])
    nk.logger_info(m.presence["session_id"])
    nk.logger_info(m.presence["username"])
    nk.logger_info(m.presence["node"])

    for _, p in ipairs(m.properties) do
      nk.logger_info(p)
    end
  end

  if #matched_users ~= 2 then
    return nil
  end

  if matched_users[1].properties["mode"] ~= "authoritative" then
    return nil
  end

  if matched_users[2].properties["mode"] ~= "authoritative" then
    return nil
  end

  return nk.match_create("match", { debug = true, expected_users = matched_users })
end

nk.register_matchmaker_matched(matchmaker_matched)

register_req_after #

Register a function with the server which will be executed after every non-realtime message as specified while registering the function.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each message.
id string REQUIREDThe specific message name to execute the function after.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local function my_func(context, payload)
  -- Run some code.
end

nk.register_req_after(my_func, "FriendsAdd")

register_req_before #

Register a function with the server which will be executed before any non-realtime message with the specified message name.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each message.
id string REQUIREDThe specific message name to execute the function after.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local function my_func(context, payload)
  -- Run some code.
  return payload -- Important!
end

nk.register_req_before(my_func, "FriendsAdd")

register_rpc #

Registers a function for use with client RPC to the server.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each RPC message.
id string REQUIREDThe unique identifier used to register the function for RPC.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local function my_func(context, payload)
  -- Run some code.
  return payload
end

nk.register_rpc(my_func, "my_func_id")

register_rt_after #

Register a function with the server which will be executed after every realtime message with the specified message name.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each msgname message.
id string REQUIREDThe specific message name to execute the function after.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local function my_func(context, payload)
  -- Run some code.
end

nk.register_rt_after(my_func, "ChannelJoin")

register_rt_before #

Register a function with the server which will be executed before any realtime message with the specified message name.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each msgname message. The function should pass the payload input back as a return argument so the pipeline can continue to execute the standard logic.
id string REQUIREDThe specific message name to execute the function after.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local function my_func(context, payload)
  -- Run some code.
  return payload -- Important!
end

nk.register_rt_before(my_func, "ChannelJoin")

register_tournament_end #

Registers a function to be run when a tournament ends.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each tournament end.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local function my_func(ctx, leaderboard, reset)
  -- Custom logic
end

nk.register_tournament_end(my_func)

register_tournament_reset #

Registers a function to be run when a tournament resets.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed on each tournament reset.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local function my_func(ctx, leaderboard, reset)
  -- Custom logic
end

nk.register_tournament_reset(my_func)

run_once #

Registers a function to be run only once.

Parameters
NameDefaultDescription
fn function REQUIREDA function reference which will be executed only once.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local function insert_user(context)
  -- This is to create a system ID that cannot be used via a client.
  local system_id = context.env["SYSTEM_ID"]

  nk.sql_exec([[
    INSERT INTO users (id, username)
    VALUES ($1, $2)
    ON CONFLICT (id) DO NOTHING
  ]], { system_id, "system_id" })
end

nk.run_once(insert_user)

Leaderboards #

leaderboard_create #

Setup a new dynamic leaderboard with the specified ID and various configuration settings. The leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.

Parameters
NameDefaultDescription
leaderboardID string REQUIREDThe unique identifier for the new leaderboard. This is used by clients to submit scores.
authoritative bool REQUIREDfalseMark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly.
sortOrder stringThe sort order for records in the leaderboard. Possible values are "asc" or "desc".
operator stringThe operator that determines how scores behave when submitted; possible values are "best", "set", or "incr".
resetSchedule stringThe cron format used to define the reset schedule for the leaderboard. This controls when a leaderboard is reset and can be used to power daily/weekly/monthly leaderboards.
metadata tableThe metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local authoritative = false
local sort = "desc"
local operator = "best"
local reset = "0 0 * * 1"

local metadata = {
  weather_conditions = "rain"
}

nk.leaderboard_create(id, authoritative, sort, operator, reset, metadata)

leaderboard_delete #

Delete a leaderboard and all scores that belong to it.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
nk.leaderboard_delete(id)

leaderboard_list #

Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.

Parameters
NameDefaultDescription
categoryStart number REQUIREDFilter leaderboards with categories greater or equal than this value.
categoryEnd number REQUIREDFilter leaderboards with categories equal or less than this value.
limit number10Return only the required number of leaderboards denoted by this limit value.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
leaderboardList tableA list of leaderboard results and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
local category_start = 1
local category_end = 2
local limit = 100  -- Number to list per page.

local leaderboards = nk.leaderboard_list(category_start, category_end, limit)

for i, leaderboard in ipairs(leaderboards) do
  nk.logger_info(string.format("ID: %q - can enter? %q", leaderboard.id, leaderboard.can_enter))
end

leaderboard_record_delete #

Remove an owner's record from a leaderboard, if one exists.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to delete from.
owner string REQUIREDThe owner of the score to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"

nk.leaderboard_record_delete(id, owner)

leaderboard_records_haystack #

Fetch the list of leaderboard records around the owner.

Parameters
NameDefaultDescription
id string REQUIREDThe ID of the leaderboard to list records for.
ownerId string REQUIREDThe owner ID around which to show records.
limit number10Return only the required number of leaderboard records denoted by this limit value. Between 1-100.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
expiry number0Time since epoch in seconds. Must be greater than 0.
Returns
NameDescription
records tableA list of leaderboard records.
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
1
2
3
4
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"

nk.leaderboard_records_haystack(id, owner, 10)

leaderboard_records_list #

List records on the specified leaderboard, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured leaderboard sort order.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to list. Mandatory field.
owners table REQUIREDList of owners to filter to.
limit numberThe maximum number of records to return (Max 10,000).
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
records tableA page of leaderboard records.
ownerRecords tableA list of owner leaderboard records (empty if the owners input parameter is not set).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
error errorAn optional error value if an error occurred.
1
2
3
4
5
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owners = {}
local limit = 10

local records, owner_records, next_cursor, prev_cursor = nk.leaderboard_records_list(id, owners, limit)

leaderboard_record_write #

Use the preconfigured operator for the given leaderboard to submit a score for a particular user.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to submit to.
owner string REQUIREDThe owner of this score submission.
username stringThe owner username of this score submission, if it's a user.
score number0The score to submit.
subscore number0A secondary subscore parameter for the submission.
metadata tableThe metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
Returns
NameDescription
record tableThe newly created leaderboard record.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local metadata = {
  weather_conditions = "rain"
}

local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local username = "02ebb2c8"
local score = 10
local subscore = 0

nk.leaderboard_record_write(id, owner, username, score, subscore, metadata)

leaderboards_get_id #

Fetch one or more leaderboards by ID.

Parameters
NameDefaultDescription
ids table REQUIREDThe table array of leaderboard ids.
Returns
NameDescription
leaderboards tableThe leaderboard records according to ID.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local leaderboard_ids = {
  "3ea5608a-43c3-11e7-90f9-7b9397165f34",
  "447524be-43c3-11e7-af09-3f7172f05936"
}

local leaderboards = nk.leaderboards_get_id(leaderboard_ids)

Logger #

logger_debug #

Write a DEBUG level message to the server logs.

Parameters
NameDefaultDescription
message string REQUIREDThe message to write to server logs with DEBUG level severity.
vars vars REQUIREDVariables to replace placeholders in message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local message = string.format("%q - %q", "hello", "world")
nk.logger_debug(message)

logger_error #

Write an ERROR level message to the server logs.

Parameters
NameDefaultDescription
message string REQUIREDThe message to write to server logs with ERROR level severity.
vars vars REQUIREDVariables to replace placeholders in message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local message = string.format("%q - %q", "hello", "world")
nk.logger_error(message)

logger_info #

Write an INFO level message to the server logs.

Parameters
NameDefaultDescription
message string REQUIREDThe message to write to server logs with INFO level severity.
vars vars REQUIREDVariables to replace placeholders in message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local message = string.format("%q - %q", "hello", "world")
nk.logger_info(message)

logger_warn #

Write a WARN level message to the server logs.

Parameters
NameDefaultDescription
message string REQUIREDThe message to write to server logs with WARN level severity.
vars vars REQUIREDVariables to replace placeholders in message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local message = string.format("%q - %q", "hello", "world")
nk.logger_warn(message)

Matches #

match_create #

Create a new authoritative realtime multiplayer match running on the given runtime module name. The given params are passed to the match's init hook.

Parameters
NameDefaultDescription
module string REQUIREDThe name of an available runtime module that will be responsible for the match. This was registered in InitModule.
params anyAny value to pass to the match init hook.
Returns
NameDescription
matchId stringThe match ID of the newly created match. Clients can immediately use this ID to join the match.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
-- Assumes you've registered a runtime module with a path of "some/folder/module.lua".
local module = "some.folder.module"

local params = {
  some = "data"
}

local match_id = nk.match_create(module, params)

match_get #

Get information on a running match.

Parameters
NameDefaultDescription
id string REQUIREDThe ID of the match to fetch.
Returns
NameDescription
match tableInformation for the running match.
error errorAn optional error value if an error occurred.
1
2
local match_id = "52f02f3e-5b48-11eb-b182-0f5058adfcc6"
local match_data = nk.match_get(match_id)

match_list #

List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.

Parameters
NameDefaultDescription
limit number1The maximum number of matches to list.
authoritative boolfalseSet true to only return authoritative matches, false to only return relayed matches.
label stringA label to filter authoritative matches by. Default "" means any label matches.
minSize numberInclusive lower limit of current match participants.
maxSize numberInclusive upper limit of current match participants.
query stringAdditional query parameters to shortlist matches.
Returns
NameDescription
match tableA table of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
-- List at most 10 matches, not authoritative, and that
-- have between 2 and 4 players currently participating.
local limit = 10
local authoritative = false
local label = nil
local min_size = 2
local max_size = 4

local matches = nk.match_list(limit, authoritative, label, min_size, max_size)

for _, m in ipairs(matches) do
  local message = string.format("Found match with id: %q", m.match_id)
  nk.logger_info(message)
end

match_signal #

Allow the match handler to be sent a reservation signal to mark a user ID or session ID into the match state ahead of their join attempt and eventual join flow. Called when the match handler receives a runtime signal.

Parameters
NameDefaultDescription
id string REQUIREDThe user ID or session ID to send a reservation signal for.
data string REQUIREDAn arbitrary input supplied by the runtime caller of the signal.
Returns
NameDescription
state anyAn (optionally) updated state. May be any non-nil value, or nil to end the match.
data stringArbitrary data to return to the runtime caller of the signal. May be a string or nil.
error errorAn optional error value if an error occurred.
1
2
3
local match_id = "52f02f3e-5b48-11eb-b182-0f5058adfcc6"
local data = "<SignalData>"
local response = nk.match_signal(match_id, data)

Metrics #

metrics_counter_add #

Add a custom metrics counter.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics counter.
tags table REQUIREDThe metrics tags associated with this counter.
delta number REQUIREDAn integer value to update this metric with.
Returns
NameDescription
1
2
3
4
5
6
7
local name = "metricName"
local tags = {
  -- Metrics tags for this counter.
}
local delta = 100

nk.metrics_counter_add(name, tags, delta)

metrics_gauge_set #

Add a custom metrics gauge.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics gauge.
tags table REQUIREDThe metrics tags associated with this gauge.
value number REQUIREDA value to update this metric with.
Returns
NameDescription
1
2
3
4
5
6
7
local name = "metricName"
local tags = {
  -- Metrics tags for this counter.
}
local value = 3.14

nk.metrics_gauge_set(name, tags, value)

metrics_timer_record #

Add a custom metrics timer.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics timer.
tags table REQUIREDThe metrics tags associated with this timer.
value number REQUIREDAn integer value to update this metric with (in nanoseconds).
Returns
NameDescription
1
2
3
4
5
6
7
local name = "metricName"
local tags = {
  -- Metrics tags for this counter.
}
local value = 100000000000

nk.metrics_timer_record(name, tags, value)

Notifications #

notifications_delete #

Delete one or more in-app notifications.

Parameters
NameDefaultDescription
notifications table REQUIREDA list of notifications to be deleted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local notification_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"

local notifications = {user_id = user_id, notification_id = notification_id}

local friends = nk.notifications_delete(notifications)

notification_send #

Send one in-app notification to a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the user to be sent the notification.
subject string REQUIREDNotification subject.
content table REQUIREDNotification content. Must be set but can be an empty table.
code number REQUIREDNotification code to use. Must be equal or greater than 0.
sender stringThe sender of this notification. If left empty, it will be assumed that it is a system notification.
persistent boolfalseWhether to record this in the database for later listing.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local subject = "You've unlocked level 100!"

local content = {
  reward_coins = 1000
}

local receiver_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local sender_id = "dcb891ea-a311-4681-9213-6741351c9994"
local code = 101
local persistent = true

nk.notification_send(receiver_id, subject, content, code, sender_id, persistent)

notification_send_all #

Send an in-app notification to all users.

Parameters
NameDefaultDescription
subject string REQUIREDNotification subject.
content table REQUIREDNotification content. Must be set but can be an empty table.
code number REQUIREDNotification code to use. Must be greater than or equal to 0.
persistent boolfalseWhether to record this in the database for later listing.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
local subject = "You've unlocked level 100!"

local content = {
  reward_coins = 1000
}

local code = 101
local persistent = true

nk.notification_send_all(subject, content, code, persistent)

notifications_send #

Send one or more in-app notifications to a user.

Parameters
NameDefaultDescription
notifications table REQUIREDA list of notifications to be sent together.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
local subject = "You've unlocked level 100!"

local content = {
  reward_coins = 1000
}

local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c" -- who to send
local sender_id = "dcb891ea-a311-4681-9213-6741351c9994" -- who the message if from
local code = 101

local new_notifications = {
  {
    subject = subject,
    content = content,
    sender_id = sender_id,
    user_id = user_id,
    code = code,
    persistent = true
  }
}

nk.notifications_send(new_notifications)

Purchases #

purchase_get_by_transaction_id #

Look up a purchase receipt by transaction ID.

Parameters
NameDefaultDescription
transactionId string REQUIREDTransaction ID of the purchase to look up.
Returns
NameDescription
owner stringThe owner of the purchase.
purchase tableA validated purchase and its owner.
error errorAn optional error value if an error occurred.
1
2
local transaction_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local purchases = nk.purchase_get_by_transaction_id(transaction_id)

purchases_list #

List stored validated purchase receipts.

Parameters
NameDefaultDescription
userId stringFilter by user ID. Can be an empty string to list purchases for all users.
limit number100Limit number of records retrieved.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
listPurchases tableA page of stored validated purchases and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
1
2
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local purchases = nk.purchases_list(user_id)

purchase_validate_apple #

Validates and stores the purchases present in an Apple App Store Receipt.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDBase-64 encoded receipt data returned by the purchase operation itself.
persist booltruePersist the purchase so that seenBefore can be computed to protect against replay attacks.
passwordOverride stringOverride the iap.apple.shared_password provided in your configuration.
Returns
NameDescription
validation tableThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = "<base64-receipt-data>"

local validation = nk.purchase_validate_apple(user_id, receipt)

purchase_validate_google #

Validates and stores a purchase receipt from the Google Play Store.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDJSON encoded Google receipt.
persist booltruePersist the purchase so that seenBefore can be computed to protect against replay attacks.
clientEmailOverride stringOverride the iap.google.client_email provided in your configuration.
privateKeyOverride stringOverride the iap.google.private_key provided in your configuration.
Returns
NameDescription
validation tableThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = '{"json":{"orderId ":"..","packageName ":"..","productId ":"..","purchaseTime":1607721533824,"purchaseState":0,"purchaseToken":"..","acknowledged":false},"signature ":"..","skuDetails ":{"productId":"..","type":"inapp","price":"u20ac82.67","price_amount_micros":82672732,"price_currency_code":"EUR","title":"..","description":"..","skuDetailsToken":".."}}'

local validation = nk.purchase_validate_google(user_id, receipt)

purchase_validate_huawei #

Validates and stores a purchase receipt from the Huawei App Gallery.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDThe Huawei receipt data.
signature string REQUIREDThe receipt signature.
persist booltruePersist the purchase so that seenBefore can be computed to protect against replay attacks.
Returns
NameDescription
validation tableThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
5
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = "<receipt-data>"
local signature = "<signature-data>"

local validation = nk.purchase_validate_huawei(user_id, receipt, signature)

Sessions #

session_disconnect #

Disconnect a session.

Parameters
NameDefaultDescription
sessionId string REQUIREDThe ID of the session to be disconnected.
reason REQUIREDThe reason for the session disconnect.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
local session_id = "085f7e38-5f15-4147-80e0-9f75bec47b89"
local reason = 0

nk.session_disconnect(session_id, reason)

session_logout #

Log out a user from their current session.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to be logged out.
token string REQUIREDThe current session authentication token.
refreshToken string REQUIREDThe current session refresh token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local token = "<AuthToken>"
local refresh_token = "<RefreshToken>"

nk.session_logout(user_id, token, refresh_token)

Storage #

storage_delete #

Remove one or more objects by their collection/keyname and optional user.

Parameters
NameDefaultDescription
objectIds table REQUIREDA list of object identifiers to be deleted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local friend_user_id = "8d98ee3f-8c9f-42c5-b6c9-c8f79ad1b820"

local object_ids = {
  { collection = "save", key = "save1", user_id = user_id },
  { collection = "save", key = "save2", user_id = user_id },
  { collection = "public", key = "progress", user_id = friend_user_id }
}

nk.storage_delete(object_ids)

storage_list #

List records in a collection and page through results. The records returned can be filtered to those owned by the user or "" for public records.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to list records for or "" (empty string) for public records.
collection string REQUIREDCollection to list data from.
limit number100Limit number of records retrieved.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
objects tableA list of storage objects.
cursor stringPagination cursor.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local records = nk.storage_list(user_id, "collection", 10, "")

for _, r in ipairs(records) do
  local m = string.format("read: %q, write: %q, value: %q", r.permission_read, r.permission_write, r.value)
  nk.logger_info(m)
end

storage_read #

Fetch one or more records by their bucket/collection/keyname and optional user.

Parameters
NameDefaultDescription
objectIds table REQUIREDA table of object identifiers to be fetched.
Returns
NameDescription
objects tableA list of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"

local object_ids = {
  { collection = "save", key = "save1", user_id = user_id },
  { collection = "save", key = "save2", user_id = user_id },
  { collection = "save", key = "save3", user_id = user_id }
}

local objects = nk.storage_read(object_ids)

for _, r in ipairs(objects) do
  local message = string.format("read: %q, write: %q, value: %q", r.permission_read, r.permission_write, r.value)
  nk.logger_info(message)
end

storage_write #

Write one or more objects by their collection/keyname and optional user.

Parameters
NameDefaultDescription
objectIds table REQUIREDA table of object identifiers to be written.
Returns
NameDescription
acks tableA list of acks with the version of the written objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"

local new_objects = {
  { collection = "save", key = "save1", user_id = user_id, value = {} },
  { collection = "save", key = "save2", user_id = user_id, value = {} },
  { collection = "save", key = "save3", user_id = user_id, value = {}, permission_read = 2, permission_write = 1 },
  { collection = "save", key = "save3", user_id = user_id, value = {}, version="*", permission_read = 1, permission_write = 1 }
}

nk.storage_write(new_objects)

Streams #

stream_close #

Close a stream and remove all presences on it.

Parameters
NameDefaultDescription
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

nk.stream_close(stream_obj)

stream_count #

Get a count of stream presences.

Parameters
NameDefaultDescription
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
Returns
NameDescription
countByStream numberNumber of current stream presences.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local count = nk.stream_count(stream_obj)

stream_send #

Send data to presences on a stream.

Parameters
NameDefaultDescription
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
data string REQUIREDThe data to send.
presences table REQUIREDTable of presences to receive the sent data. If not set, will be sent to all presences.
reliable bool REQUIREDtrueWhether the sender has been validated prior.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local data = "<Data>"
local presences = {} -- table of presences to send the data to
local reliable = true

nk.stream_send(stream_obj, data, presences, reliable)

stream_send_raw #

Send a message to presences on a stream.

Parameters
NameDefaultDescription
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
msg REQUIREDThe message to send.
presences table REQUIREDTable of presences to receive the sent data. If not set, will be sent to all presences.
reliable bool REQUIREDtrueWhether the sender has been validated prior.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local data = {} -- table that conforms to a Go &rtapi.Envelope object
local presences = {} -- table of presences to send the data to
local reliable = true

nk.stream_send_raw(stream_obj, data, presences, reliable)

stream_user_get #

Retreive a stream presence and metadata by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to fetch information for.
sessionId string REQUIREDThe current session ID for the user.
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
Returns
NameDescription
meta tablePresence and metadata for the user.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"

local stream_obj = {
  mode = 0,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local user = nk.stream_user_get(user_id, session_id, stream_obj)

stream_user_join #

Add a user to a stream.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be added.
sessionId string REQUIREDThe current session ID for the user.
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
hidden boolfalseWhether the user will be marked as hidden.
persistence booltrueWhether message data should be stored in the database.
status stringUser status message.
Returns
NameDescription
success boolWhether the user was successfully added.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"

local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local hidden = false
local persistence = true
local status = ""

local success = nk.stream_user_join(user_id, session_id, stream_obj, hidden, persistence, status)

stream_user_kick #

Kick user(s) from a stream.

Parameters
NameDefaultDescription
presence table REQUIREDThe presence(s) to be kicked.
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
local presence_obj = {
  user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed",
  node = "<Node>"
}

local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

nk.stream_user_kick(presence_obj, stream_obj)

stream_user_leave #

Remove a user from a stream.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be removed.
sessionId string REQUIREDThe current session ID for the user.
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"

local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

nk.stream_user_leave(user_id, session_id, stream_obj)

stream_user_list #

List all users currently online and connected to a stream.

Parameters
NameDefaultDescription
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
includeHidden booltrueInclude stream presences marked as hidden in the results.
includeNotHidden booltrueInclude stream presences not marked as hidden in the results.
Returns
NameDescription
presences tableTable of stream presences and their information.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local stream_obj = {
  mode = 0,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local include_hidden = true
local include_not_hidden = true

local presences = nk.stream_user_list(stream_obj, include_hidden, include_not_hidden)

stream_user_update #

Update a stream user by ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be updated.
sessionId string REQUIREDThe current session ID for the user.
stream table REQUIREDA stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
hidden boolfalseWhether the user will be marked as hidden.
persistence booltrueWhether message data should be stored in the database.
status stringUser status message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"

local stream_obj = {
  mode = 4,
  subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
  subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
  label = ""
}

local hidden = false
local persistence = true
local status = "Updated status"

local success = nk.stream_user_update(user_id, session_id, stream_obj, hidden, persistence, status)

Subscriptions #

subscription_get_by_product_id #

Look up a subscription by product ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the subscription owner.
productId string REQUIREDTransaction ID of the purchase to look up.
Returns
NameDescription
owner stringThe owner of the purchase.
purchase tableA validated purchase and its owner.
error errorAn optional error value if an error occurred.
1
2
3
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local product_id = "subscriptionId"
local subscriptions = nk.subscription_get_by_product_id(user_id, product_id)

subscriptions_list #

List stored validated subscription receipts.

Parameters
NameDefaultDescription
userId stringFilter by user ID. Can be an empty string to list subscriptions for all users.
limit number100Limit number of records retrieved.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
listPurchases tableA page of stored validated subscriptions and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
1
2
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local subscriptions = nk.subscriptions_list(user_id)

subscription_validate_apple #

Validates and stores the subscription present in an Apple App Store Receipt.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDBase-64 encoded receipt data returned by the subscription operation itself.
persist booltruePersist the subscription.
passwordOverride stringOverride the iap.apple.shared_password provided in your configuration.
Returns
NameDescription
validation tableThe resulting successfully validated subscriptions.
error errorAn optional error value if an error occurred.
1
2
3
4
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = "<base64-receipt-data>"

local validation = nk.subscriptions_validate_apple(user_id, receipt)

subscription_validate_google #

Validates and stores a subscription receipt from the Google Play Store.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDJSON encoded Google receipt.
persist booltruePersist the subscription.
clientEmailOverride stringOverride the iap.google.client_email provided in your configuration.
privateKeyOverride stringOverride the iap.google.private_key provided in your configuration.
Returns
NameDescription
validation tableThe resulting successfully validated subscriptions.
error errorAn optional error value if an error occurred.
1
2
3
4
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = '{"json":{"orderId ":"..","packageName ":"..","productId ":"..","purchaseTime":1607721533824,"purchaseState":0,"purchaseToken":"..","acknowledged":false},"signature ":"..","skuDetails ":{"productId":"..","type":"inapp","price":"u20ac82.67","price_amount_micros":82672732,"price_currency_code":"EUR","title":"..","description":"..","skuDetailsToken":".."}}'

local validation = nk.subscription_validate_google(user_id, receipt)

Tournaments #

tournament_add_attempt #

Add additional score attempts to the owner's tournament record. This overrides the max number of score attempts allowed in the tournament for this specific owner.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament to update.
owner string REQUIREDThe owner of the records to increment the count for.
count number REQUIREDThe number of attempt counts to increment. Can be negative to decrease count.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "leaderboard-record-owner"
local count = -10

nk.tournament_add_attempt(id, owner, count)

tournament_create #

Setup a new dynamic tournament with the specified ID and various configuration settings. The underlying leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the new tournament. This is used by clients to submit scores.
authoritative booltrueWhether the tournament created is server authoritative.
sortOrder stringThe sort order for records in the tournament. Possible values are "asc" or "desc".
operator stringThe operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr".
resetSchedule stringThe cron format used to define the reset schedule for the tournament. This controls when the underlying leaderboard resets and the tournament is considered active again.
metadata tableThe metadata you want associated to the tournament. Some good examples are weather conditions for a racing game.
title stringThe title of the tournament.
description stringThe description of the tournament.
category numberA category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127.
startTime numberThe start time of the tournament. Leave empty for immediately or a future time.
endTime numberneverThe end time of the tournament. When the end time is elapsed, the tournament will not reset and will cease to exist. Must be greater than startTime if set.
duration number REQUIREDThe active duration for a tournament. This is the duration when clients are able to submit new records. The duration starts from either the reset period or tournament start time whichever is sooner. A game client can query the tournament for results between end of duration and next reset period.
maxSize numberMaximum size of participants in a tournament.
maxNumScore numberMaximum submission attempts for a tournament record.
joinRequired boolfalseWhether the tournament needs to be joined before a record write is allowed.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local authoritative = false
local sort = "desc"     -- One of: "desc", "asc".
local operator = "best" -- One of: "best", "set", "incr".
local reset = "0 12 * * *" -- Noon UTC each day.

local metadata = {
  weather_conditions = "rain"
}

title = "Daily Dash"
description = "Dash past your opponents for high scores and big rewards!"
category = 1
start_time = 0       -- Start now.
end_time = 0         -- Never end, repeat the tournament each day forever.
duration = 3600      -- In seconds.
max_size = 10000     -- First 10,000 players who join.
max_num_score = 3    -- Each player can have 3 attempts to score.
join_required = true -- Must join to compete.
nk.tournament_create(id, sort, operator, duration, reset, metadata, title, description, category, start_time, end_time, max_size, max_num_score, join_required)

tournament_delete #

Delete a tournament and all records that belong to it.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
nk.tournament_delete(id)

tournament_join #

A tournament may need to be joined before the owner can submit scores. This operation is idempotent and will always succeed for the owner even if they have already joined the tournament.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament to join.
userId string REQUIREDThe owner of the record.
username string REQUIREDThe username of the record owner.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "leaderboard-record-owner"
local username = "myusername"

nk.tournament_join(id, owner, username)

tournament_list #

Find tournaments which have been created on the server. Tournaments can be filtered with categories and via start and end times.

Parameters
NameDefaultDescription
categoryStart number REQUIREDFilter tournament with categories greater or equal than this value.
categoryEnd number REQUIREDFilter tournament with categories equal or less than this value.
startTime numberFilter tournament with that start after this time.
endTime numberFilter tournament with that end before this time.
limit number10Return only the required number of tournament denoted by this limit value.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
tournamentList tableA list of tournament results and possibly a cursor and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
local category_start = 1
local category_end = 2
local start_time = 1538147711
local end_time = 0 -- All tournaments from the start time.
local limit = 100  -- Number to list per page.
local tournaments = nk.tournament_list(category_start, category_end, start_time, end_time, limit)

for i, tournament in ipairs(tournaments) do
  nk.logger_info(string.format("ID: %q - can enter? %q", tournament.id, tournament.can_enter))
end

tournament_records_haystack #

Fetch the list of tournament records around the owner.

Parameters
NameDefaultDescription
id string REQUIREDThe ID of the tournament to list records for.
ownerId string REQUIREDThe owner ID around which to show records.
limit number10Return only the required number of tournament records denoted by this limit value. Between 1-100.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
expiry number0Time since epoch in seconds. Must be greater than 0.
Returns
NameDescription
records tableA page of tournament records.
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
1
2
3
4
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"

nk.tournament_records_haystack(id, owner, 10)

tournament_records_list #

List records on the specified tournament, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured tournament sort order.

Parameters
NameDefaultDescription
tournamentId string REQUIREDThe ID of the tournament to list records for.
ownerIds tableList of owner IDs to filter results by.
limit number REQUIREDReturn only the required number of tournament records denoted by this limit value. Max is 10000.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiry number0Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
NameDescription
records tableA page of tournament records.
ownerRecords tableA list of owner tournament records (empty if the owners input parameter is not set).
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owners = {"4c2ae592-b2a7-445e-98ec-697694478b1c", "2c751239-e87a-4b5f-bc06-56873038339d"}
local limit = 100
local cursor = ""
local override_expiry = 0

local records = nk.tournament_records_list(id, owners, limit, cursor, override_expiry)

tournament_record_write #

Submit a score and optional subscore to a tournament leaderboard. If the tournament has been configured with join required this will fail unless the owner has already joined the tournament.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament leaderboard to submit to.
owner string REQUIREDThe owner of this score submission.
username stringThe owner username of this score submission, if it's a user.
score number0The score to submit.
subscore number0A secondary subscore parameter for the submission.
Returns
NameDescription
metadata tableThe metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
result tableThe newly created leaderboard record.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local username = "02ebb2c8"
local score = 10
local subscore = 0

local metadata = {
  weather_conditions = "rain"
}

nk.tournament_record_write(id, owner, username, score, subscore, metadata)

tournaments_get_id #

Fetch one or more tournaments by ID.

Parameters
NameDefaultDescription
ids table REQUIREDThe table of tournament ids.
Returns
NameDescription
tournamentIDs tableList of tournament records.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local tournament_ids = {
  "3ea5608a-43c3-11e7-90f9-7b9397165f34",
  "447524be-43c3-11e7-af09-3f7172f05936"
}

local tournaments = nk.tournaments_get_id(tournament_ids)

Users #

multi_update #

Update account, storage, and wallet information simultaneously.

Parameters
NameDefaultDescription
accountUpdates table REQUIREDList of account information to be updated.
storageWrites table REQUIREDList of storage objects to be updated.
walletUpdates table REQUIREDList of wallet updates to be made.
updateLedger boolfalseWhether to record this wallet update in the ledger.
Returns
NameDescription
storageWriteAcks tableA list of acks with the version of the written objects.
walletUpdateAcks tableA list of wallet updates results.
error errorAn optional error value if an error occurred.
1
2
3
4
5
local account_updates = {} -- table of account update objects
local storage_writes = {} -- table of storage write objects
local wallet_updates = {} -- table of wallet_update objects
local update_ledger = true
local results = nk.multi_update(account_updates, storage_writes, wallet_updates, update_ledger)

users_ban_id #

Ban one or more users by ID.

Parameters
NameDefaultDescription
userIds table REQUIREDA table of user IDs to ban.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local user_ids = {
  "3ea5608a-43c3-11e7-90f9-7b9397165f34",
  "447524be-43c3-11e7-af09-3f7172f05936"
}

nk.users_ban_id(user_ids)

users_get_id #

Fetch one or more users by ID.

Parameters
NameDefaultDescription
userIds table REQUIREDA Lua table of user IDs to fetch.
Returns
NameDescription
users tableA table of user record objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local user_ids = {
  "3ea5608a-43c3-11e7-90f9-7b9397165f34",
  "447524be-43c3-11e7-af09-3f7172f05936"
}

local users = nk.users_get_id(user_ids)

for _, u in ipairs(users) do
  local message = string.format("username: %q, displayname: %q", u.username, u.display_name)
  nk.logger_info(message)
end

users_get_random #

Fetch one or more users randomly.

Parameters
NameDefaultDescription
count int REQUIREDThe number of users to fetch.
Returns
NameDescription
users tableA list of user record objects.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local users = nk.users_get_random(100)

for _, u in ipairs(users) do
  local message = string.format("id: %q, displayname: %q", u.user_id, u.display_name)
  nk.logger_info(message)
end

users_get_username #

Fetch one or more users by username.

Parameters
NameDefaultDescription
usernames table REQUIREDA table of usernames to fetch.
Returns
NameDescription
users tableA table of user record objects.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local usernames = {"b7865e7e", "c048ba7a"}
local users = nk.users_get_username(usernames)

for _, u in ipairs(users) do
  local message = string.format("id: %q, displayname: %q", u.user_id, u.display_name)
  nk.logger_info(message)
end

users_unban_id #

Unban one or more users by ID.

Parameters
NameDefaultDescription
userIds table REQUIREDA table of user IDs to unban.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local user_ids = {
  "3ea5608a-43c3-11e7-90f9-7b9397165f34",
  "447524be-43c3-11e7-af09-3f7172f05936"
}

nk.users_unban_id(user_ids)

Utils #

aes128_decrypt #

Decrypt an aes128 encrypted string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decrypted.
key string REQUIREDThe 16 Byte decryption key.
Returns
NameDescription
clearText stringThe deciphered input.
error errorAn optional error value if an error occurred.
1
local plaintext = nk.aes128_decrypt("48656C6C6F20776F726C64", "goldenbridge_key")

aes128_encrypt #

aes128 encrypt a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be aes128 encrypted.
key string REQUIREDThe 16 Byte encryption key.
Returns
NameDescription
cipherText stringThe ciphered input.
error errorAn optional error value if an error occurred.
1
local cyphertext = nk.aes128_encrypt("48656C6C6F20776F726C64", "goldenbridge_key")

aes256_decrypt #

Decrypt an aes256 encrypted string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decrypted.
key string REQUIREDThe 32 Byte decryption key.
Returns
NameDescription
clearText stringThe deciphered input.
error errorAn optional error value if an error occurred.
1
local plaintext = nk.aes256_decrypt("48656C6C6F20776F726C64", "goldenbridge_key")

aes256_encrypt #

aes256 encrypt a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be aes256 encrypted.
key string REQUIREDThe 32 Byte encryption key.
Returns
NameDescription
cipherText stringThe ciphered input.
error errorAn optional error value if an error occurred.
1
local cyphertext = nk.aes256_encrypt("48656C6C6F20776F726C64", "goldenbridge_key")

base16_decode #

Decode a base16 encoded string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decoded.
Returns
NameDescription
output stringDecoded string.
error errorAn optional error value if an error occurred.
1
2
local decoded = nk.base16_decode("48656C6C6F20776F726C64")
nk.logger_info(decoded) -- outputs "Hello world".

base16_encode #

base16 encode a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be encoded.
Returns
NameDescription
output stringEncoded string.
error errorAn optional error value if an error occurred.
1
2
local encoded = nk.base16_encode("Hello world")
nk.logger_info(encoded) -- outputs "48656C6C6F20776F726C64"

base64_decode #

Decode a base64 encoded string.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be base64 decoded.
Returns
NameDescription
output stringDecoded string.
error errorAn optional error value if an error occurred.
1
2
local decoded = nk.base64_decode("SGVsbG8gd29ybGQ=")
nk.logger_info(decoded) -- outputs "Hello world".

base64_encode #

Base64 encode a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be base64 encoded.
Returns
NameDescription
output stringEncoded string.
error errorAn optional error value if an error occurred.
1
2
local encoded = nk.base64_encode("Hello world")
nk.logger_info(encoded) -- outputs "SGVsbG8gd29ybGQ="

base64url_decode #

Decode a base64 URL encoded string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decoded.
Returns
NameDescription
output stringDecoded string.
error errorAn optional error value if an error occurred.
1
2
local decoded = nk.base64url_decode("SGVsbG8gd29ybGQ=")
nk.logger_info(decoded) -- outputs "Hello world".

base64url_encode #

Base64 URL encode a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be base64 URL encoded.
Returns
NameDescription
output stringEncoded string.
error errorAn optional error value if an error occurred.
1
2
local encoded = nk.base64url_encode("Hello world")
nk.logger_info(encoded) -- outputs "SGVsbG8gd29ybGQ="

bcrypt_compare #

Compare hashed input against a plaintext input.

Parameters
NameDefaultDescription
hash string REQUIREDThe bcrypted input string.
plaintext string REQUIREDPlaintext input to compare against.
Returns
NameDescription
result boolTrue if they are the same, false otherwise.
error errorAn optional error value if an error occurred.
1
2
local is_same = nk.bcrypt_compare("$2a$04$bl3tac7Gwbjy04Q8H2QWLuUOEkpoNiAeTxazxi4fVQQRMGbMaUHQ2", "123456")
nk.logger_info(is_same) -- outputs true.

bcrypt_hash #

Generate one-way hashed string using bcrypt.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to bcrypt.
Returns
NameDescription
hash stringHashed string.
error errorAn optional error value if an error occurred.
1
2
local hashed = nk.bcrypt_hash("Hello World")
nk.logger_info(hashed)

cron_next #

Parses a CRON expression and a timestamp in UTC seconds, and returns the next matching timestamp in UTC seconds.

Parameters
NameDefaultDescription
expression string REQUIREDA valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight).
timestamp number REQUIREDA time value expressed as UTC seconds.
Returns
NameDescription
next_ts numberThe next UTC seconds timestamp (number) that matches the given CRON expression, and is immediately after the given timestamp.
error errorAn optional error value if an error occurred.
1
2
3
4
5
-- Based on the current time, return the UTC seconds value representing the
-- nearest upcoming Monday at 00:00 UTC (midnight.)
local expr = "0 0 * * 1"
local ts = os.time()
local next = nk.cron_next(expr, ts)

file_read #

Read file from user device.

Parameters
NameDefaultDescription
relPath string REQUIREDRelative path to the file to be read.
Returns
NameDescription
fileContent stringThe read file contents.
error errorAn optional error value if an error occurred.
1
2
local relative_path = "<RelativePath>"
local contents = nk.file_read(relative_path)

hmac_sha256_hash #

Create a HMAC-SHA256 hash from input and key.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
key string REQUIREDThe hashing key.
Returns
NameDescription
mac stringHashed input as a string using the key.
error errorAn optional error value if an error occurred.
1
2
local hash = nk.hmac_sha256_hash("encryptthis", "somekey")
print(hash)

http_request #

Send a HTTP request that returns a data type containing the result of the HTTP response.

Parameters
NameDefaultDescription
url string REQUIREDThe URL of the web resource to request.
method string REQUIREDThe HTTP method verb used with the request.
headers tableA table of headers used with the request.
content stringThe bytes to send with the request.
timeout number5000Timeout of the request in milliseconds.
Returns
NameDescription
returnVal tableCode, Headers, and Body response values for the HTTP response.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
local url = "https://google.com/"
local method = "HEAD"

local headers = {
    ["Content-Type"] = "application/json",
    ["Accept"] = "application/json"
}

local content = nk.json_encode({}) -- encode table as JSON string
local timeout = 5000 -- 5 seconds timeout
local success, code, headers, body = pcall(nk.http_request, url, method, headers, content, timeout)

if (not success) then
  nk.logger_error(string.format("Failed %q", code))
elseif (code >= 400) then
  nk.logger_error(string.format("Failed %q %q", code, body))
else
  nk.logger_info(string.format("Success %q %q", code, body))
end

json_decode #

Decode the JSON input as a Lua table.

Parameters
NameDefaultDescription
jsonString string REQUIREDThe JSON encoded input.
Returns
NameDescription
jsonData tableDecoded JSON input as a Lua table.
error errorAn optional error value if an error occurred.
1
2
local json = nk.json_decode('{"hello": "world"}')
nk.logger_info(json.hello)

json_encode #

Encode the input as JSON.

Parameters
NameDefaultDescription
value string REQUIREDThe input to encode as JSON .
Returns
NameDescription
jsonBytes stringThe encoded JSON string.
error errorAn optional error value if an error occurred.
1
2
3
4
local input = {["some"] = "json"}
local json = nk.json_encode(input)

nk.logger_info(json) -- Outputs '{"some": "json"}'.

jqt_generate #

Generate a JSON Web Token.

Parameters
NameDefaultDescription
signingMethod string REQUIREDThe signing method to be used, either HS256 or RS256.
signingKey string REQUIREDThe signing key to be used.
claims table REQUIREDThe JWT payload.
Returns
NameDescription
token stringThe newly generated JWT.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
local signing_method = "HS256"
local signing_key = "goldenbridge_key"
local claims = { email = "test@heroiclabs.com" }

local token = nk.jwt_generate(signing_method, signing_key, claims)
nk.logger_info("Token: " .. token)

md5_hash #

Create an md5 hash from the input.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
Returns
NameDescription
hash stringA string with the md5 hash of the input.
error errorAn optional error value if an error occurred.
1
2
3
4
local input = "somestring"
local hashed = nk.md5_hash(input)

nk.logger_info(hashed)

rsaSHA256Hash #

Create a RSA encrypted SHA256 hash from the input.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
key string REQUIREDThe RSA private key.
Returns
NameDescription
signature stringA string with the RSA encrypted SHA256 hash of the input.
error errorAn optional error value if an error occurred.
1
2
local cipher_text = nk.rsa_sha256_hash("Hello world", "rsa_private_key")
nk.logger_info(cipher_text)

sha256_hash #

Create an SHA256 hash from the input.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
Returns
NameDescription
hash stringA string with the SHA256 hash of the input.
error errorAn optional error value if an error occurred.
1
2
local cipher_text = nk.sha256_hash("Hello world")
nk.logger_info(cipher_text)

sql_exec #

Execute an arbitrary SQL query and return the number of rows affected. Typically an "INSERT", "DELETE", or "UPDATE" statement with no return columns.

Parameters
NameDefaultDescription
query string REQUIREDA SQL query to execute.
parameters table REQUIREDArbitrary parameters to pass to placeholders in the query.
Returns
NameDescription
count numberA list of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
-- This example query deletes all expired leaderboard records.
local query = [[
  DELETE FROM leaderboard_record
  WHERE expires_at > 0 AND expires_at <= $1
]]

local parameters = { os.time() * 1000 }

local affected_rows_count = nk.sql_exec(query, parameters)

sql_query #

Execute an arbitrary SQL query that is expected to return row data. Typically a "SELECT" statement.

Parameters
NameDefaultDescription
query string REQUIREDA SQL query to execute.
parameters table REQUIREDArbitrary parameters to pass to placeholders in the query.
Returns
NameDescription
result tableA table of rows and the respective columns and values.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
-- Example fetching a list of usernames for the 100 most recently signed up users.
local query = [[
  SELECT username, create_time
  FROM users
  ORDER BY create_time DESC
  LIMIT 100
]]

local parameters = {}

local rows = nk.sql_query(query, parameters)

-- Example of processing the rows.
nk.logger_info("Selected " .. #rows .. " rows.")

for i, row in ipairs(rows) do
  nk.logger_info(string.format("Username %q created at %q", row.username, row.create_time))
end

time #

Get the current UTC time in milliseconds using the system wall clock.

Parameters
NameDefaultDescription
Returns
NameDescription
t intA number representing the current UTC time in milliseconds.
error errorAn optional error value if an error occurred.
1
local utc_msec = nk.time()

uuid_bytes_to_string #

Convert the 16-byte raw representation of a UUID into the equivalent 36-character standard UUID string representation. Will raise an error if the input is not valid and cannot be converted.

Parameters
NameDefaultDescription
uuid_bytes string REQUIREDThe UUID bytes to convert.
Returns
NameDescription
u stringA string containing the equivalent 36-character standard representation of the UUID.
error errorAn optional error value if an error occurred.
1
2
local uuid_bytes = "896418357731323983933079013" -- some uuid bytes.
local uuid_string = nk.uuid_bytes_to_string(uuid_bytes)

uuid_string_to_bytes #

Convert the 36-character string representation of a UUID into the equivalent 16-byte raw UUID representation. Will raise an error if the input is not valid and cannot be converted.

Parameters
NameDefaultDescription
uuid_string string REQUIREDThe UUID string to convert.
Returns
NameDescription
u stringA string containing the equivalent 16-byte representation of the UUID.
error errorAn optional error value if an error occurred.
1
2
3
4
local uuid_string = "4ec4f126-3f9d-11e7-84ef-b7c182b36521" -- some uuid string.
local uuid_bytes = nk.uuid_string_to_bytes(uuid_string)

nk.logger_info(uuid_bytes)

uuid_v4 #

Generate a version 4 UUID in the standard 36-character string representation.

Parameters
NameDefaultDescription
Returns
NameDescription
u stringThe newly generated version 4 UUID identifier string.
error errorAn optional error value if an error occurred.
1
2
local uuid = nk.uuid_v4()
nk.logger_info(uuid)

Wallets #

wallet_ledger_list #

List all wallet updates for a particular user from oldest to newest.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to list wallet updates for.
limit number100Limit number of results.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
itemsTable tableA table containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters.
newCursor stringPagination cursor. Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
local updates = nk.wallet_ledger_list(user_id)

for _, u in ipairs(updates) do
  local message = string.format("Found wallet update with id: %q", u.id)
  nk.logger_info(message)
end

wallet_ledger_update #

Update the metadata for a particular wallet update in a user's wallet ledger history. Useful when adding a note to a transaction for example.

Parameters
NameDefaultDescription
itemId string REQUIREDThe ID of the wallet ledger item to update.
metadata table REQUIREDThe new metadata to set on the wallet ledger item.
Returns
NameDescription
itemTable tableThe updated wallet ledger item.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
local id = "2745ba53-4b43-4f83-ab8f-93e9b677f33a"

local metadata = {
  game_result = "loss"
}

local u = nk.wallet_ledger_update(id, metadata)

wallets_update #

Update one or more user wallets with individual changesets. This function will also insert a new wallet ledger item into each user's wallet history that tracks their update.

Parameters
NameDefaultDescription
updates table REQUIREDThe set of user wallet update operations to apply.
updateLedger boolfalseWhether to record this update in the ledger.
Returns
NameDescription
updateWallets tableA list of wallet update results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
local updates = {
  {
    user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592",
    changeset = {
      coins = 10, -- Add 10 coins to the user's wallet.
      gems = -5   -- Remove 5 gems from the user's wallet.
    },
    metadata = {
      game_result = "won"
    }
  }
}

nk.wallets_update(updates, true)

wallet_update #

Update a user's wallet with the given changeset.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user whose wallet to update.
changeset table REQUIREDThe set of wallet operations to apply.
metadata tableAdditional metadata to tag the wallet update with.
updateLedger boolfalseWhether to record this update in the ledger.
Returns
NameDescription
result tableThe changeset after the update and before to the update, respectively.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"

local changeset = {
  coins = 10, -- Add 10 coins to the user's wallet.
  gems = -5   -- Remove 5 gems from the user's wallet.
}

local metadata = {
  game_result = "won"
}

local updated, previous = nk.wallet_update(user_id, changeset, metadata, true)