> 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로 오류를 반환합니다.
사전 스크립트/사후 스크립트에서 검증(validation)을 수행하여 조건을 만족하지 않을 경우 오류를 반환하고 싶을 때 사용합니다.

### 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 레퍼런스를 참조하십시오.




