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.
User ID to fetch information for. Must be valid UUID.
Returns
Name
Description
accounttable
All account information including wallet, device IDs and more.
errorerror
An optional error value if an error occurred.
1
2
3
localaccount=nk.account_get_id("8f4d52c7-bf28-4fcf-8af2-1d4fcf685592")localwallet=account.walletnk.logger_info(string.format("Wallet is: %s",nk.json_encode(wallet)))
User ID for which the information is to be updated. Must be valid UUID.
metadatatable
The metadata to update for this account.
usernamestring
Username to be set. Must be unique. Use null if it is not being updated.
displayNamestring
Display name to be updated. Use null if it is not being updated.
timezonestring
Timezone to be updated. Use null if it is not being updated.
locationstring
Location to be updated. Use null if it is not being updated.
languagestring
Lang tag to be updated. Use null if it is not being updated.
avatarUrlstring
User's avatar URL. Use null if it is not being updated.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
localuser_id="4ec4f126-3f9d-11e7-84ef-b7c182b36521"-- Some user ID.localmetadata={}localusername=""localdisplay_name=nillocaltimezone=nillocallocation=nillocallanguage=nillocalavatar_url=nilnk.account_update_id(user_id,metadata,username,display_name,timezone,location,language,avatar_url)
The UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsernamestring
The username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persistbool
true
Whether to record this message in the channel history.
Returns
Name
Description
acktable
Message sent ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
localcontent={}content["message"]="hello"localcreate_ack=nk.channel_message_send("<ChannelId>",content,"<SenderId>","<SenderUsername>",true)nk.logger_info("%q created at %q",create_ack.messageId,create_ack.createTime)
The UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsernamestring
The username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persistbool
true
Whether to record this message in the channel history.
Returns
Name
Description
acktable
Message updated ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
localcontent={}content["message"]="hello"localupdate_ack=nk.channel_message_update("<ChannelId>","<MessageId>",content,"<SenderId>","<SenderUsername>",true)nk.logger_info("%q created at %q",update_ack.messageId,update_ack.createTime)
List all friends, invites, invited, and blocked which belong to a user.
Parameters
Name
Default
Description
userIdstringREQUIRED
The ID of the user whose friends, invites, invited, and blocked you want to list.
limitnumber
The number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
statenumber
The state of the friendship with the user. If unspecified this returns friends in all states for the user.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
friendstable
The user information for users that are friends of the current user.
cursorstring
An 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.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
localuser_id="b1aafe16-7540-11e7-9738-13777fcc7cd8"locallimit=100localstate=nillocalcursor=nillocalfriends=nk.friends_list(user_id,limit,state,cursor)for_,minipairs(friends)do-- States are: friend(0), invite_sent(1), invite_received(2), blocked(3)localmsg=string.format("Friend username %q has state %q",m.user.username,m.state)nk.logger_info(msg)end
List all friends, invites, invited, and blocked which belong to a user.
Parameters
Name
Default
Description
userIdstringREQUIRED
The ID of the user whose friends, invites, invited, and blocked you want to list.
limitnumber
The number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
friendsOfFriendstable
The user information for users that are friends of friends of the current user.
cursorstring
An 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.
A list of strings of the IDs for the groups to get.
Returns
Name
Description
getGroupstable
A table of groups with their fields.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
localgroup_ids={"0BF154F1-F7D1-4AAA-A060-5FFED3CDB982","997C0D18-0B25-4AEC-8331-9255BD36665D"}localgroups=nk.groups_get_id(group_ids)for_,ginipairs(groups)dolocalmsg=string.format("Group name %q with id %q",g.name,g.id)nk.logger_info(msg)end
Search for groups that contain this value in their name.
langTagstring
Filter based upon the entered language tag.
membersnumberREQUIRED
Search by number of group members.
openboolREQUIRED
Filter based on whether groups are Open or Closed.
limitnumber
100
Return only the required number of groups denoted by this limit value.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
cursorstring
An 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.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
localgroup_name="Heroic"locallang_tag="en"localmembers=10localopen=truelocallimit=100localgroups=nk.groups_list(group_name,lang_tag,members,open,limit)fori,groupinipairs(groups)donk.logger_info(string.format("ID: %q - can enter? %q",group.id,group.can_enter))end
List all members, admins and superadmins which belong to a group. This also list incoming join requests.
Parameters
Name
Default
Description
groupIdstringREQUIRED
The ID of the group to list members for.
limitint
100
The maximum number of entries in the listing.
stateint
null
The state of the user within the group. If unspecified this returns users in all states.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
groupUserstable
The user information for members, admins and superadmins for the group. Also users who sent a join request.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
localgroup_id="a1aafe16-7540-11e7-9738-13777fcc7cd8"localmembers=nk.group_users_list(group_id)for_,minipairs(members)dolocalmsg=string.format("Member username %q has state %q",m.user.username,m.state)nk.logger_info(msg)end
List all groups which a user belongs to and whether they've been accepted or if it's an invite.
Parameters
Name
Default
Description
userIdstringREQUIRED
The ID of the user to list groups for.
Returns
Name
Description
userGroupstable
A table of groups with their fields.
cursorstring
An optional next page cursor that can be used to retrieve the next page of records (if any).
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
localuser_id="64ef6cb0-7512-11e7-9e52-d7789d80b70b"localgroups=nk.user_groups_list(user_id)for_,ginipairs(groups)dolocalmsg=string.format("User has state %q in group %q",g.state,g.group.name)nk.logger_info(msg)end
Register a function with the server which will be executed before any realtime message with the specified message name.
Parameters
Name
Default
Description
fnfunctionREQUIRED
A 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.
idstringREQUIRED
The specific message name to execute the function after.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
localfunctionmy_func(context,payload)-- Run some code.returnpayload-- Important!endnk.register_rt_before(my_func,"ChannelJoin")
A function reference which will be executed only once.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
localfunctioninsert_user(context)-- This is to create a system ID that cannot be used via a client.localsystem_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"})endnk.run_once(insert_user)
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
Name
Default
Description
leaderboardIDstringREQUIRED
The unique identifier for the new leaderboard. This is used by clients to submit scores.
authoritativeboolREQUIRED
false
Mark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly.
sortOrderstring
The sort order for records in the leaderboard. Possible values are "asc" or "desc".
operatorstring
The operator that determines how scores behave when submitted; possible values are "best", "set", or "incr".
resetSchedulestring
The 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.
metadatatable
The metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game.
enableRanksbool
false
Whether to enable rank values for the leaderboard.
Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.
Parameters
Name
Default
Description
limitnumber
10
Return only the required number of leaderboards denoted by this limit value.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
leaderboardListtable
A list of leaderboard results and possibly a cursor. If cursor is empty/nil there are no further results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
locallimit=100-- Number to list per page.localleaderboards=nk.leaderboard_list(limit)fori,leaderboardinipairs(leaderboards)donk.logger_info(string.format("ID: %q - can enter? %q",leaderboard.id,leaderboard.can_enter))end
Fetch the list of leaderboard records around the owner.
Parameters
Name
Default
Description
idstringREQUIRED
The ID of the leaderboard to list records for.
ownerIdstringREQUIRED
The owner ID around which to show records.
limitnumber
10
Return only the required number of leaderboard records denoted by this limit value. Between 1-100.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
expirynumber
0
Time since epoch in seconds. Must be greater than 0.
Returns
Name
Description
recordstable
A list of leaderboard records.
prevCursorstring
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursorstring
An 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.
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
Name
Default
Description
idstringREQUIRED
The unique identifier for the leaderboard to list. Mandatory field.
ownerstableREQUIRED
List of owners to filter to.
limitnumber
The maximum number of records to return (Max 10,000).
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiryint
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
recordstable
A page of leaderboard records.
ownerRecordstable
A list of owner leaderboard records (empty if the owners input parameter is not set).
nextCursorstring
An 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.
prevCursorstring
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
Build a cursor to be used with leaderboardRecordsList to fetch records starting at a given rank. Only available if rank cache is not disabled for the leaderboard.
Parameters
Name
Default
Description
leaderboardIDstringREQUIRED
The unique identifier of the leaderboard.
ranknumberREQUIRED
The rank to start listing leaderboard records from.
overrideExpirynumber
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
leaderboardListCursorstring
A string cursor to be used with leaderboardRecordsList.
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
Name
Default
Description
modulestringREQUIRED
The name of an available runtime module that will be responsible for the match. This was registered in InitModule.
paramsany
Any value to pass to the match init hook.
Returns
Name
Description
matchIdstring
The match ID of the newly created match. Clients can immediately use this ID to join the match.
errorerror
An 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".localmodule="some.folder.module"localparams={some="data"}localmatch_id=nk.match_create(module,params)
List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.
Parameters
Name
Default
Description
limitnumber
1
The maximum number of matches to list.
authoritativebool
nil
Set true to only return authoritative matches, false to only return relayed matches and nil to return both.
labelstring
A label to filter authoritative matches by. Default "" means any label matches.
minSizenumber
Inclusive lower limit of current match participants.
maxSizenumber
Inclusive upper limit of current match participants.
querystring
Additional query parameters to shortlist matches.
Returns
Name
Description
matchtable
A table of matches matching the parameters criteria.
errorerror
An 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.locallimit=10localauthoritative=falselocallabel=nillocalmin_size=2localmax_size=4localmatches=nk.match_list(limit,authoritative,label,min_size,max_size)for_,minipairs(matches)dolocalmessage=string.format("Found match with id: %q",m.match_id)nk.logger_info(message)end
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
Name
Default
Description
idstringREQUIRED
The user ID or session ID to send a reservation signal for.
datastringREQUIRED
An arbitrary input supplied by the runtime caller of the signal.
Returns
Name
Description
stateany
An (optionally) updated state. May be any non-nil value, or nil to end the match.
datastring
Arbitrary data to return to the runtime caller of the signal. May be a string or nil.
localsubject="You've unlocked level 100!"localcontent={reward_coins=1000}localuser_id="4c2ae592-b2a7-445e-98ec-697694478b1c"-- who to sendlocalsender_id="dcb891ea-a311-4681-9213-6741351c9994"-- who the message if fromlocalcode=101localnew_notifications={{subject=subject,content=content,sender_id=sender_id,user_id=user_id,code=code,persistent=true}}nk.notifications_send(new_notifications)
Collection of storage engine to index objects from.
keystringREQUIRED
Key of storage objects to index. Set to empty string to index all objects of collection.
fieldstableREQUIRED
A table of strings with the keys of the storage object whose values are to be indexed.
sortableFieldstable
A table of strings with the keys of the storage object whose values are to be sortable. The keys must exist within the previously specified fields to be indexed.
maxEntriesintREQUIRED
Maximum number of entries kept in the index.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
localname="IndexName"localcollection="CollectionName"localkey="KeyName"localfields={"field1","field2"}-- Only objects containing any of these keys and respective values are indexed.localmaxEntries=1000localerr=nk.register_storage_index(name,collection,key,fields,maxEntries)
A function reference which will be executed on each storage object to be written that is a candidate for the index.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
localname="index_name"functionindexFilter(context,logger,nk,storageWrite)-- Inspect object to decide if it should be inserted or tentatively deleted.returntrueendlocalerr=nk.register_storage_index_filter(name,indexFilter)
The storage object fields to sort the query results by. The prefix '-' before a field name indicates descending order. All specified fields must be indexed and sortable.
callerIdstring
User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed.
A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
datastringREQUIRED
The data to send.
presencestableREQUIRED
Table of presences to receive the sent data. If not set, will be sent to all presences.
reliableboolREQUIRED
true
Whether the sender has been validated prior.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
localstream_obj={mode=4,subject="87fc43cf-16f1-4852-8fd3-12c07caccf7e",subcontext="085f7e38-5f15-4147-80e0-9f75bec47b89",label=""}localdata="<Data>"localpresences={}-- table of presences to send the data tolocalreliable=truenk.stream_send(stream_obj,data,presences,reliable)
A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string).
msgREQUIRED
The message to send.
presencestableREQUIRED
Table of presences to receive the sent data. If not set, will be sent to all presences.
reliableboolREQUIRED
true
Whether the sender has been validated prior.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
localstream_obj={mode=4,subject="87fc43cf-16f1-4852-8fd3-12c07caccf7e",subcontext="085f7e38-5f15-4147-80e0-9f75bec47b89",label=""}localdata={}-- table that conforms to a Go &rtapi.Envelope objectlocalpresences={}-- table of presences to send the data tolocalreliable=truenk.stream_send_raw(stream_obj,data,presences,reliable)
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
Name
Default
Description
idstringREQUIRED
The unique identifier for the tournament to update.
ownerstringREQUIRED
The owner of the records to increment the count for.
countnumberREQUIRED
The number of attempt counts to increment. Can be negative to decrease count.
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
Name
Default
Description
idstringREQUIRED
The unique identifier for the new tournament. This is used by clients to submit scores.
authoritativebool
true
Whether the tournament created is server authoritative.
sortOrderstring
The sort order for records in the tournament. Possible values are "asc" or "desc".
operatorstring
The operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr".
resetSchedulestring
The 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.
metadatatable
The metadata you want associated to the tournament. Some good examples are weather conditions for a racing game.
titlestring
The title of the tournament.
descriptionstring
The description of the tournament.
categorynumber
A category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127.
startTimenumber
The start time of the tournament. Leave empty for immediately or a future time.
endTimenumber
never
The 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.
durationnumberREQUIRED
The 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.
maxSizenumber
Maximum size of participants in a tournament.
maxNumScorenumber
1000000
Maximum submission attempts for a tournament record.
joinRequiredbool
false
Whether the tournament needs to be joined before a record write is allowed.
localid="4ec4f126-3f9d-11e7-84ef-b7c182b36521"localauthoritative=falselocalsort="desc"-- One of: "desc", "asc".localoperator="best"-- One of: "best", "set", "incr".localreset="0 12 * * *"-- Noon UTC each day.localmetadata={weather_conditions="rain"}title="Daily Dash"description="Dash past your opponents for high scores and big rewards!"category=1start_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.enable_ranks=falsenk.tournament_create(id,sort,operator,duration,reset,metadata,title,description,category,start_time,end_time,max_size,max_num_score,join_required,enable_ranks)
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.
Find tournaments which have been created on the server. Tournaments can be filtered with categories and via start and end times.
Parameters
Name
Default
Description
categoryStartnumberREQUIRED
Filter tournament with categories greater or equal than this value.
categoryEndnumberREQUIRED
Filter tournament with categories equal or less than this value.
startTimenumber
Filter tournament with that start after this time.
endTimenumber
Filter tournament with that end before this time.
limitnumber
10
Return only the required number of tournament denoted by this limit value.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
tournamentListtable
A list of tournament results and possibly a cursor and possibly a cursor. If cursor is empty/nil there are no further results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
localcategory_start=1localcategory_end=2localstart_time=1538147711localend_time=0-- All tournaments from the start time.locallimit=100-- Number to list per page.localtournaments=nk.tournament_list(category_start,category_end,start_time,end_time,limit)fori,tournamentinipairs(tournaments)donk.logger_info(string.format("ID: %q - can enter? %q",tournament.id,tournament.can_enter))end
Fetch the list of tournament records around the owner.
Parameters
Name
Default
Description
idstringREQUIRED
The ID of the tournament to list records for.
ownerIdstringREQUIRED
The owner ID around which to show records.
limitnumber
10
Return only the required number of tournament records denoted by this limit value. Between 1-100.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
expirynumber
0
Time since epoch in seconds. Must be greater than 0.
Returns
Name
Description
recordstable
A page of tournament records.
prevCursorstring
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursorstring
An 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.
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
Name
Default
Description
tournamentIdstringREQUIRED
The ID of the tournament to list records for.
ownerIdstable
List of owner IDs to filter results by.
limitnumberREQUIRED
Return only the required number of tournament records denoted by this limit value. Max is 10000.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpirynumber
0
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
recordstable
A page of tournament records.
ownerRecordstable
A list of owner tournament records (empty if the owners input parameter is not set).
prevCursorstring
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursorstring
An 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.
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
Name
Default
Description
idstringREQUIRED
The unique identifier for the tournament leaderboard to submit to.
ownerstringREQUIRED
The owner of this score submission.
usernamestring
The owner username of this score submission, if it's a user.
scorenumber
0
The score to submit.
subscorenumber
0
A secondary subscore parameter for the submission.
Returns
Name
Description
metadatatable
The metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
Update account, storage, and wallet information simultaneously.
Parameters
Name
Default
Description
accountUpdatestableREQUIRED
List of account information to be updated.
storageWritestableREQUIRED
List of storage objects to be updated.
storageDeletestableREQUIRED
A list of storage objects to be deleted.
walletUpdatestableREQUIRED
List of wallet updates to be made.
updateLedgerbool
false
Whether to record this wallet update in the ledger.
Returns
Name
Description
storageWriteAckstable
A list of acks with the version of the written objects.
walletUpdateAckstable
A list of wallet updates results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
localaccount_updates={}-- table of account update objectslocalstorage_writes={}-- table of storage write objectslocalwallet_updates={}-- table of wallet_update objectslocalupdate_ledger=truelocalresults=nk.multi_update(account_updates,storage_writes,wallet_updates,update_ledger)
Parses a CRON expression and a timestamp in UTC seconds, and returns the next matching timestamp in UTC seconds.
Parameters
Name
Default
Description
expressionstringREQUIRED
A valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight).
timestampnumberREQUIRED
A time value expressed as UTC seconds.
Returns
Name
Description
next_tsnumber
The next UTC seconds timestamp (number) that matches the given CRON expression, and is immediately after the given timestamp.
errorerror
An 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.)localexpr="0 0 * * 1"localts=os.time()localnext=nk.cron_next(expr,ts)
Execute an arbitrary SQL query and return the number of rows affected. Typically an "INSERT", "DELETE", or "UPDATE" statement with no return columns.
Parameters
Name
Default
Description
querystringREQUIRED
A SQL query to execute.
parameterstableREQUIRED
Arbitrary parameters to pass to placeholders in the query.
Returns
Name
Description
countnumber
A list of matches matching the parameters criteria.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
-- This example query deletes all expired leaderboard records.localquery=[[
DELETE FROM leaderboard_record
WHERE expires_at > 0 AND expires_at <= $1
]]localparameters={os.time()*1000}localaffected_rows_count=nk.sql_exec(query,parameters)
Execute an arbitrary SQL query that is expected to return row data. Typically a "SELECT" statement.
Parameters
Name
Default
Description
querystringREQUIRED
A SQL query to execute.
parameterstableREQUIRED
Arbitrary parameters to pass to placeholders in the query.
Returns
Name
Description
resulttable
A table of rows and the respective columns and values.
errorerror
An 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.localquery=[[
SELECT username, create_time
FROM users
ORDER BY create_time DESC
LIMIT 100
]]localparameters={}localrows=nk.sql_query(query,parameters)-- Example of processing the rows.nk.logger_info("Selected "..#rows.." rows.")fori,rowinipairs(rows)donk.logger_info(string.format("Username %q created at %q",row.username,row.create_time))end
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
Name
Default
Description
uuid_bytesstringREQUIRED
The UUID bytes to convert.
Returns
Name
Description
ustring
A string containing the equivalent 36-character standard representation of the UUID.
errorerror
An optional error value if an error occurred.
1
2
localuuid_bytes="896418357731323983933079013"-- some uuid bytes.localuuid_string=nk.uuid_bytes_to_string(uuid_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
Name
Default
Description
uuid_stringstringREQUIRED
The UUID string to convert.
Returns
Name
Description
ustring
A string containing the equivalent 16-byte representation of the UUID.
errorerror
An optional error value if an error occurred.
1
2
3
4
localuuid_string="4ec4f126-3f9d-11e7-84ef-b7c182b36521"-- some uuid string.localuuid_bytes=nk.uuid_string_to_bytes(uuid_string)nk.logger_info(uuid_bytes)
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
Name
Default
Description
updatestableREQUIRED
The set of user wallet update operations to apply.
updateLedgerbool
false
Whether to record this update in the ledger.
Returns
Name
Description
updateWalletstable
A list of wallet update results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
localupdates={{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)
Additional metadata to tag the wallet update with.
updateLedgerbool
false
Whether to record this update in the ledger.
Returns
Name
Description
resulttable
The changeset after the update and before to the update, respectively.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
localuser_id="8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"localchangeset={coins=10,-- Add 10 coins to the user's wallet.gems=-5-- Remove 5 gems from the user's wallet.}localmetadata={game_result="won"}localupdated,previous=nk.wallet_update(user_id,changeset,metadata,true)