> For the complete documentation index, see [llms.txt](https://ak-scripts.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ak-scripts.gitbook.io/docs/yi-lai/markdown/gong-neng-mo-kuai-dao-chu/ku-cun-xi-tong-inventory.md).

# 库存系统（Inventory）

## 📦 Inventory（库存系统）模块导出文档

### 📋 概述

Inventory 模块是 ak-lib 的库存系统桥接层，提供了对不同库存系统（ox\_inventory、qb-inventory、qs-inventory、codem-inventory）和框架自带背包的统一抽象接口。

**重要说明**：推荐使用 `Framework()` 统一接口，它整合了 Framework 和 Inventory 的功能。直接使用 Inventory 模块的场景较少。

### 🚀 导出方式

#### 服务端

**方式 1：使用统一接口（推荐）⭐**

```lua
local FW = exports['ak-lib']:Framework()
```

**方式 2：直接使用 Inventory 模块**

```lua
local Inventory = exports['ak-lib']:InventoryModule()
```

**方式 3：单独导出函数**

```lua
local count = exports['ak-lib']:GetItem(source, 'bread')
```

### 📖 可用导出

#### 服务端

**模块对象方法**

使用 `exports['ak-lib']:InventoryModule()` 获取的对象包含以下方法：

| 方法                                          | 说明       | 参数                                                         | 返回值              |
| ------------------------------------------- | -------- | ---------------------------------------------------------- | ---------------- |
| `GetInventoryName()`                        | 获取库存系统名称 | -                                                          | string           |
| `GetItem(source, item)`                     | 获取物品数量   | `source` (number), `item` (string)                         | number           |
| `HasItem(source, item, count)`              | 检查物品     | `source`, `item`, `count` (number, 可选)                     | boolean          |
| `AddItem(source, item, count, metadata)`    | 添加物品     | `source`, `item`, `count` (number), `metadata` (table, 可选) | boolean / number |
| `RemoveItem(source, item, count, metadata)` | 移除物品     | `source`, `item`, `count` (number), `metadata` (table, 可选) | boolean / number |

**单独导出函数**

| 导出                                          | 说明       | 参数                                    | 返回值              |
| ------------------------------------------- | -------- | ------------------------------------- | ---------------- |
| `InventoryModule()`                         | 返回模块对象   | -                                     | `AKInventory` 对象 |
| `GetInventoryName()`                        | 获取库存系统名称 | -                                     | string           |
| `GetItem(source, item)`                     | 获取物品数量   | `source`, `item`                      | number           |
| `HasItem(source, item, count)`              | 检查物品     | `source`, `item`, `count`             | boolean          |
| `AddItem(source, item, count, metadata)`    | 添加物品     | `source`, `item`, `count`, `metadata` | boolean / number |
| `RemoveItem(source, item, count, metadata)` | 移除物品     | `source`, `item`, `count`, `metadata` | boolean / number |

### 💡 使用示例

#### 推荐方式：使用统一接口 ⭐

```lua
-- 推荐：使用 Framework() 统一接口
local FW = exports['ak-lib']:Framework()

-- 物品操作（自动使用 Inventory 模块）
local count = FW.GetItem(source, 'bread')
print("面包数量:", count)

-- 检查物品
if FW.HasItem(source, 'bread', 1) then
    print("玩家有至少 1 个面包")
end

-- 添加物品
FW.AddItem(source, 'bread', 5)

-- 移除物品
FW.RemoveItem(source, 'bread', 2)

-- 获取库存系统名称
local invName = FW.GetInventoryName()
print("当前库存系统:", invName)
```

#### 直接使用 Inventory 模块

```lua
-- 方式 1：使用模块对象
local Inventory = exports['ak-lib']:InventoryModule()

local count = Inventory.GetItem(source, 'bread')
if Inventory.HasItem(source, 'bread', 1) then
    Inventory.RemoveItem(source, 'bread', 1)
end

-- 方式 2：使用单独导出函数
local count = exports['ak-lib']:GetItem(source, 'bread')
exports['ak-lib']:RemoveItem(source, 'bread', 1)
```

#### 完整示例：商店购买系统

```lua
local FW = exports['ak-lib']:Framework()

RegisterServerEvent('shop:buyItem', function(itemName, count)
    local source = source
    
    -- 检查物品是否存在
    local item = ShopItems[itemName]
    if not item then
        TriggerClientEvent('ak-lib:Notify', source, {
            type = 'error',
            message = '物品不存在'
        })
        return
    end
    
    -- 计算总价
    local totalPrice = item.price * count
    
    -- 检查金钱
    if not FW.HasItem(source, 'money', totalPrice) then
        TriggerClientEvent('ak-lib:Notify', source, {
            type = 'error',
            message = '金钱不足'
        })
        return
    end
    
    -- 检查背包空间（通过添加物品的返回值判断）
    local added = FW.AddItem(source, itemName, count)
    if not added then
        TriggerClientEvent('ak-lib:Notify', source, {
            type = 'error',
            message = '背包空间不足'
        })
        return
    end
    
    -- 移除金钱
    FW.RemoveMoney(source, 'cash', totalPrice, '购买物品')
    
    -- 通知成功
    TriggerClientEvent('ak-lib:Notify', source, {
        type = 'success',
        message = string.format('成功购买 %d 个 %s', count, itemName)
    })
end)
```

### 📝 API 详细说明

#### 支持的库存系统

1. **ox\_inventory** - 优先检测
2. **qb-inventory**
3. **qs-inventory**
4. **codem-inventory**
5. **框架自带背包** - ESX/QBCore/QBX 框架自带的背包系统

#### 自动检测机制

模块启动时会自动检测服务器上运行的库存系统，检测顺序：

1. ox\_inventory
2. qb-inventory
3. qs-inventory
4. codem-inventory
5. 框架自带背包（作为兜底）

#### GetInventoryName() 返回值

* `'ox_inventory'` - ox\_inventory
* `'qb-inventory'` - qb-inventory
* `'qs-inventory'` - qs-inventory
* `'codem-inventory'` - codem-inventory
* `'esx'` / `'qb'` / `'qbx'` - 框架自带背包
* `'unknown'` - 未初始化或未检测到

#### 失败语义说明

* **返回 `false`**：操作失败（可能是：玩家不存在、背包不存在、物品不存在、背包已满等）
* **返回 `true` 或 `number`**：操作成功
  * `AddItem` 可能返回添加的数量（number）
  * `RemoveItem` 可能返回移除的数量（number）

#### metadata 参数

某些库存系统支持物品元数据（metadata），可以通过 `metadata` 参数传递：

```lua
-- 添加带元数据的物品（示例）
FW.AddItem(source, 'weapon_pistol', 1, {
    serial = 'ABC123',
    durability = 100
})
```

**注意**：不是所有库存系统都支持 metadata，使用前请确认。

### ⚠️ 注意事项

1. **推荐使用统一接口**：使用 `exports['ak-lib']:Framework()` 获取 `AKFW` 对象，而不是直接访问 `AKInventory`。
2. **初始化顺序**：Inventory 模块会等待 Framework 模块初始化完成后再进行检测。
3. **防御性编程**：所有函数都包含参数检查和空值处理，未初始化时返回安全默认值。
4. **金钱处理**：
   * 使用 `ox_inventory` 时，金钱操作必须使用 Inventory 模块（通过 Framework 统一接口）
   * 使用其他库存系统时，金钱操作使用框架的金钱系统
5. **返回值处理**：`AddItem` 和 `RemoveItem` 的返回值可能是 `boolean` 或 `number`，需要根据实际情况处理。
6. **物品数量**：`GetItem` 返回的是物品数量（number），如果物品不存在则返回 0。
7. **库存系统差异**：不同库存系统的行为可能有差异，建议在目标库存系统上充分测试。
8. **元数据支持**：不是所有库存系统都支持 `metadata` 参数，使用前请确认。
9. **服务端专用**：Inventory 模块只能在服务端使用。

### 🔗 相关文档

* 库存系统说明
* Framework 模块导出文档


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ak-scripts.gitbook.io/docs/yi-lai/markdown/gong-neng-mo-kuai-dao-chu/ku-cun-xi-tong-inventory.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
