Utility methods of GS2-Script

Description of utility methods available in Lua scripts executed by GS2-Script

Extension methods available in GS2-Script extension scripts (Lua language).

The Lua standard library is restricted inside the GS2-Script sandbox. Functions that load external resources or that catch errors internally — such as load, require, dofile, and pcall — are not available. The os library is also restricted for safety; only os.time() can be used. The table, string, and math libraries are available almost as-is.

util.table_to_json

Convert a Lua table type (array) to a JSON format string.

Request

Argument name Type Description
table table Lua table

Result

Member name Type Description
isError bool presence of error
statusCode int status code
errorMessage string error message
result string JSON string of the conversion result

Sample

Code

result = util.table_to_json({a="a", b=1, c=false})
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
json_str = result["result"]

Output

{"a":"a","b":1,"c":false}

util.json_to_table

Converts a string in JSON format to a Lua table type (array).

Request

Argument name Type Description
jsonText string string in JSON format
disableNumberStringToNumber bool Do not convert to numeric type when a numeric value is stored in JSON as a string type (default: false)

Result

Member name Type Description
isError bool presence of error
statusCode int status code
errorMessage string error message
result table Lua table of conversion results

Sample

Code

result = util.json_to_table("{\"a\": \"a\", \"b\": 1, \"c\": false}")
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
json_table = result["result"]

util.split

Split a string.

Request

Argument name Type Description
value string original string
sep string delimiter

Result

Member name Type Description
isError bool presence of error
statusCode int status code
errorMessage string error message
result table Lua table of split strings

Sample

Code

result = util.split("a,b,c", ",")
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
split_table = result["result"]
print(split_table[1])
print(split_table[2])
print(split_table[3])

Output

a
b
c

http.get

Issues HTTP GET requests.

Request

Argument name Type Description
url string URL of the connection

Result

Member name Type Description
isError bool presence of error
statusCode int status code
errorMessage string error message
result string HTTP Response Body

Sample

Code

result = http.get("https://example.com")
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
get_result = result["result"]

http.post

Issue an HTTP POST request.

Request

Argument name Type Description
url string URL of the connection
contentType string Content-Type of the HTTP header
body string HTTP request message body

Result

Member name Type Description
isError bool presence of error
statusCode int status code
errorMessage string error message
result string HTTP Response Body

Sample

Code

result = http.post("https://example.com", "application/json", "{\"a\": 1}")
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
post_result = result["result"]

util.random

Generate a random floating point number between 0 and 1.

Request

Argument name Type Description

Result

member name type description
isError bool presence of error
statusCode int status code
errorMessage string error message
result float generated random number

Sample

Code

result = util.random()
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
random_value = result["result"]

util.uuid

Generate strings based on UUIDv4

Request

Argument name Type Description

Result

member name type description
isError bool presence of error
statusCode int status code
errorMessage string error message
result float generated random number

Sample

Code

result = util.uuid()
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
random_value = result["result"]

util.shared_random

Generates a deterministic random number based on a seed and a counter, designed for use cases such as drawing systems where the same random sequence must be reproducible. The sequence is preserved across automatic re-executions of a stamp sheet, so the same values are obtained even when a transaction is retried.

A separate counter is maintained per category, allowing multiple independent random sequences to be used within the same script.

Request

Argument name Type Description
category int Category number used to distinguish random sequences

Result

Member name Type Description
isError bool presence of error
statusCode int status code
errorMessage string error message
result float generated random number

Sample

Code

result = util.shared_random(1)
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end
shared_value = result["result"]

fail

Aborts script execution as a failure and returns an error to the API that invoked the script. Use it in pre-/post-scripts to perform validation and return an error when conditions are not met.

Request

Argument name Type Description
errorCode string Error code to return (BadRequest / Unauthorized / NotFound / Conflict / ServiceUnavailable / BadGateway, etc. HTTP status codes such as 400 or 401 are also accepted)
message string Error message

If errorCode does not match any of the known values, the error is treated as InternalServerError.

Sample

if not_allowed then
  fail("BadRequest", "validation.error.notAllowed")
end

print

Outputs an arbitrary string to the log. When GS2-Log is enabled, the printed content can be confirmed from the access logs. Use it for debugging within scripts or to record execution paths.

Request

Argument name Type Description
message string Message to log

Sample

print("invoked with userId=" .. args.userId)

os.time

Returns the server time at the moment the script is executed as a Unix timestamp (in seconds). If you are using the GS2-Distributor time-offset feature, the returned time reflects that offset.

Sample

now = os.time()

gs2

A client for calling GS2 microservice APIs directly from within a Lua script in GS2-Script. Pass the service name as the argument, then chain the API name and its arguments.

If the invoked API issues a transaction, that transaction is returned together with the transaction of the API that originally launched the script.

Sample

Fetching an item from GS2-Inventory:

result = gs2("inventory").get_item_set_by_user_id({
  namespaceName = "namespace-0001",
  userId = args.userId,
  inventoryName = "inventory-0001",
  itemName = "item-0001",
})
if result.isError then
  fail(result['statusCode'], result['errorMessage'])
end

For the list of available service names and API names, see the API reference of each microservice.