> For the complete documentation index, see [llms.txt](/llms.txt)

# GS2-Script のユーティリティメソッド

GS2-Script で実行する Lua スクリプト内で利用可能なユーティリティメソッドの説明




GS2-Scriptの拡張スクリプト（Lua言語）で使用可能な拡張メソッドです。

GS2-Script のサンドボックス内で利用できる Lua 標準ライブラリには制限があります。
`load` / `require` / `dofile` / `pcall` のような外部リソースを読み込んだり、エラーを内部でハンドリングしたりする関数は使用できません。
`os` ライブラリも安全のため、`os.time()` のみが利用可能です。
`table` / `string` / `math` ライブラリは概ねそのまま利用できます。

## util.table_to_json

Luaのテーブル型（配列）を、JSON形式の文字列に変換します。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| table | table | Luaテーブル |

### Result

| メンバ名 | 型 | 説明 |
| ----- | -- | --- |
| isError | bool | エラーの有無 |
| statusCode | int | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | string | 変換結果のJSON文字列 |

### Sample

#### Code

```lua
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

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

---

## util.json_to_table

JSON形式の文字列を、Luaのテーブル型（配列）に変換します。

### Request

| 引数名                         | 型      | 説明                                               |
|-----------------------------|--------|--------------------------------------------------|
| jsonText                    | string | JSON形式の文字列                                       |
| disableNumberStringToNumber | bool   | JSON内に文字列型で数値が格納されていた時に数値型に変換しない(default: false) |

### Result

| メンバ名 | 型 | 説明 |
| ----- | -- | --- |
| isError | bool | エラーの有無 |
| statusCode | int | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | table | 変換結果のLuaテーブル |

### Sample

#### Code

```lua
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

文字列を分割します。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| value | string | 元の文字列 |
| sep | string | デリミタ、区切り文字列 |

### Result

| メンバ名 | 型 | 説明 |
| ----- | -- | --- |
| isError | bool | エラーの有無 |
| statusCode | int | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | table | 分割した文字列のLuaテーブル |

### Sample

#### Code

```lua
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

```text
a
b
c
```

---

## http.get

HTTPのGETリクエストを発行します。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| url | string | 接続先のURL |

### Result

| メンバ名 | 型 | 説明 |
| ----- | -- | --- |
| isError | bool | エラーの有無 |
| statusCode | int | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | string | HTTPレスポンスのボディ |

### Sample

#### Code

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

---

## http.post

HTTPのPOSTリクエストを発行します。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| url | string | 接続先のURL |
| contentType | string | HTTPヘッダーのContent-Type |
| body | string | HTTPリクエストメッセージのボディ |

### Result

| メンバ名 | 型 | 説明 |
| ----- | -- | --- |
| isError | bool | エラーの有無 |
| statusCode | int | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | string | HTTPレスポンスのボディ |

### Sample

#### Code

```lua
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

0 〜 1 の浮動小数点数の乱数を生成する

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |

### Result

| メンバ名 | 型      | 説明       |
| ----- |--------|----------|
| isError | bool   | エラーの有無   |
| statusCode | int    | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | float  | 生成した乱数   |

### Sample

#### Code

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

## util.uuid

UUIDv4 に基づく文字列を生成する

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |

### Result

| メンバ名 | 型      | 説明       |
| ----- |--------|----------|
| isError | bool   | エラーの有無   |
| statusCode | int    | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | float  | 生成したUUID |

### Sample

#### Code

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

---

## util.shared_random

抽選機能などで《同一の乱数列を再現したい》ケースのために、シードと連番に基づく決定論的な乱数を生成します。
スタンプシートの自動リトライによる再実行時にも、同じ乱数列が得られるように設計されています。

`category` ごとに独立した連番が管理されるため、同一スクリプト内で複数の独立した乱数列が必要な場合に使い分けられます。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| category | int | 乱数列を区別するためのカテゴリ番号 |

### Result

| メンバ名 | 型 | 説明 |
| ----- | -- | --- |
| isError | bool | エラーの有無 |
| statusCode | int | ステータスコード |
| errorMessage | string | エラーメッセージ |
| result | float | 生成した乱数 |

### Sample

#### Code

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

---

## fail

スクリプトの実行を失敗扱いで中断し、呼び出し元の API にエラーを返します。
事前スクリプト/事後スクリプトでバリデーションを行い、条件を満たさない場合にエラーを返したい場合に使用します。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| errorCode | string | 返却するエラーコード（`BadRequest` / `Unauthorized` / `NotFound` / `Conflict` / `ServiceUnavailable` / `BadGateway` 等。HTTP ステータスコード（`400` / `401` 等）も指定可能） |
| message | string | エラーメッセージ |

`errorCode` に該当しない値を指定した場合は `InternalServerError` として処理されます。

### Sample

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

---

## print

ログに任意の文字列を出力します。GS2-Log を有効化している場合、出力した内容はアクセスログから確認できます。
スクリプト内のデバッグや、実行経路の記録に利用してください。

### Request

| 引数名 | 型 | 説明 |
| ----- | -- | --- |
| message | string | 出力するメッセージ |

### Sample

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

---

## os.time

スクリプトの実行時点のサーバー時刻を Unix 時間（秒）で取得します。
GS2-Distributor の時刻オフセット機能を利用している場合、その分のオフセットが反映された時刻が返ります。

### Sample

```lua
now = os.time()
```

---

## gs2

GS2-Script の Lua スクリプト内から、GS2 の各マイクロサービスの API を直接呼び出すためのクライアントです。
呼び出すサービス名を引数に取り、続けて API 名と引数を指定します。

呼び出した API がトランザクションを発行する場合、その発行内容はスクリプトを起動した API のトランザクションと合わせて返却されます。

### Sample

GS2-Inventory のアイテムを取得する例:

```lua
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
```

利用可能なサービス名・API 名は、各マイクロサービスの API リファレンスを参照してください。




