This commit is contained in:
Luke committed 2023-06-04 15:15:21 +02:00
1 parent 3cebaf7fa5
commit b5eba8423f
229 files changed
+6238 -10690

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
# Client events
This is not a comprehensive list of events and is missing events intended for internal use only.
## Triggers
These events are safe to trigger and handle in other scripts.
### ox_inventory:disarm
Can be triggered to force the player to disarm.
```lua
TriggerClientEvent('ox_inventory:disarm', playerId, noAnim)
```
## Handlers
These events shouldn't be triggered by any other scripts.
### ox_inventory:updateInventory
Triggered after inventory slots have been updated, included on load.
Changes is a table containing all updated slot data indexed by slotId. Empty slots are "false".
```lua
AddEventHandler('ox_inventory:updateInventory', function(changes) end)
```
- changes: `table<number, table | false>`
### ox_inventory:currentWeapon
Triggered when a weapon is equipped or its metadata is altered.
```lua
AddEventHandler('ox_inventory:currentWeapon', function(weapon) end)
```
- weapon?: `table`
### ox_inventory:itemCount
Triggered when the amount of an item in the player's inventory is changed.
_Note: Not available for ESX, use esx:addInventoryItem or esx:removeInventoryItem._
```lua
AddEventHandler('ox_inventory:itemCount', function(itemName, totalCount) end)
```
+26
View File
@@ -0,0 +1,26 @@
# Server events
This is not a comprehensive list of events and is missing events intended for internal use only.
## Handlers
These events shouldn't be triggered by any other scripts.
### ox_inventory:openedInventory
Triggered after an inventory is opened by a player.
```lua
AddEventHandler('ox_inventory:openedInventory', function(playerId, inventoryId) end)
```
- playerId: `number`
- inventoryId: `string`
### ox_inventory:closeInventory
Triggered after an inventory is closed by a player.
```lua
AddEventHandler('ox_inventory:closeInventory', function(playerId, inventoryId) end)
```
+74
View File
@@ -0,0 +1,74 @@
---
title: ESX
---
import { Tabs, Tab } from 'nextra-theme-docs';
## Compatibility
Ox Inventory is a complete replacement for existing item, inventory, and weapon systems; it is inherently incompatible with ESX and any resources that rely on default behaviour.
- Loadouts do not exist and weapons are treated as items.
- Standard shops and stashes (i.e. esx_shops, esx_weaponshop, and esx_policejob).
- Resources that alter the default esx inventory or provide a ui (i.e. esx_trunkinventory, esx_inventoryhud).
## Installation
- Use a compatible version of [ESX Legacy](https://github.com/esx-framework/esx-legacy) (1.6.0+).
- Modify your `server.cfg`, starting ox_inventory immediately after es_extended.
```yaml
start oxmysql
start ox_lib
start es_extended
start qtarget
start ox_inventory
```
## Convert ESX inventory data
- Start the server and type `convertinventory esx` into the server console.
- Optionally, type `convertinventory esxproperty` into the server console.
- Restart the server once conversion is complete.
## Optional optimisation
All item related functions from xPlayer, such as `xPlayer.getInventoryItem`, have been modified for compatibility purposes; however they are considered deprecated.
The reasoning is fairly simple - there's now additional function references and overhead to consider. Fortunately, the new Inventory functions can be used directly and offer a great deal of improvements over the old ones.
You should read through the functions section for further information, but the following should give you a decent idea.
<Tabs items={["ESX", "Ox Inventory"]}>
<Tab>
```lua
if xPlayer.getInventoryItem('acetone').count > 2 and xPlayer.getInventoryItem('antifreeze').count > 4 and xPlayer.getInventoryItem('sudo').count > 9 then
xPlayer.removeInventoryItem("acetone", 3)
xPlayer.removeInventoryItem("antifreeze", 5)
xPlayer.removeInventoryItem("sudo", 10)
end
```
</Tab>
<Tab>
Add the following code somewhere in your resource to cache the exports metatable.
```lua
local ox_inventory = exports.ox_inventory
```
You will be able to reference any functions exposed through the export.
```lua
local items = ox_inventory:Search(source, 'count', {'acetone', 'antifreeze', 'sudo'})
if items and items.acetone > 2 and items.antifreeze > 4 and items.sudo > 9 then
ox_inventory:RemoveItem(source, 'acetone', 3)
ox_inventory:RemoveItem(source, 'antifreeze', 5)
ox_inventory:RemoveItem(source, 'sudo', 10)
end
```
</Tab>
</Tabs>
+89
View File
@@ -0,0 +1,89 @@
---
title: QBCore
---
import { Callout } from 'nextra/components';
import { Tabs, Tab } from 'nextra-theme-docs';
<Callout type="warning">
QBCore support is experimental and cannot work as a "drag and drop" solution due to many incompatibilities.
</Callout>
## Compatibility
Ox Inventory provides a complete suite of tools to replace the built-in items and inventory system from QBCore, and is not intended to be used with resources designed around it.
- Stashes used by qb-inventory and its forks do not work, but can _possibly_ be converted.
- Remove `qb-inventory` (or similar), or qb-core will not function properly.
- Remove `qb-shops` and `qb-weapons`, as they depend on `qb-inventory` and conflict.
- Weapon holstering and draw animations (like in `qb-smallresources`) may break our own methods.
## Qbox Project
Qbox is a fork of QBCore being developed by a team of former contributors and developers on QBCore. The team is focused on improving performance and security, as well as converting resources to support our resources (mainly ox_lib and ox_inventory).
We _strongly_ advise using Qbox as an alternative to QBCore.
- [Qbox Project GitHub](https://github.com/Qbox-project/)
- [Qbox Project Discord](https://discord.gg/AtbwBuJHN5)
## Installation
- Setup [qb-core](https://github.com/qbcore-framework) or [qbox](https://github.com/Qbox-project/qb-core).
- Edit your `server.cfg`.
- Add `setr inventory:framework "qb"` before starting your resources.
- Start ox_inventory immediately after qb-core.
### Convert QBCore
If you have existing player data, you will need to convert it to a compatible format.
- Start the server and type `convertinventory qb` into the server console.
- Restart the server once conversion is complete.
## Optional optimisation
All item related functions from Player, such as `Player.Functions.GetItemByName`, have been modified for compatibility purposes; however they are considered deprecated.
The reasoning is fairly simple - there's now additional function references and overhead to consider. Fortunately, the new Inventory functions can be used directly and offer a great deal of improvements over the old ones.
You should read through the functions section for further information, but the following should give you a decent idea.
<Tabs items={["QBCore", "Ox Inventory"]}>
<Tab>
```lua
local acetone = Player.Functions.GetItemByName('acetone')
local antifreeze = Player.Functions.GetItemByName('antifreeze')
local sudo = Player.Functions.GetItemByName('sudo')
if acetone?.amount > 2 and antifreeze?.amount > 4 and sudo?.amount > 9 then
Player.Functions.RemoveItem("acetone", 3)
Player.Functions.RemoveItem("antifreeze", 5)
Player.Functions.RemoveItem("sudo", 10)
end
```
</Tab>
<Tab>
Add the following code somewhere in your resource to cache the exports metatable.
```lua
local ox_inventory = exports.ox_inventory
```
You will be able to reference any functions exposed through the export.
```lua
local items = ox_inventory:Search(source, 'count', {'acetone', 'antifreeze', 'sudo'})
if items and items.acetone > 2 and items.antifreeze > 4 and items.sudo > 9 then
ox_inventory:RemoveItem(source, 'acetone', 3)
ox_inventory:RemoveItem(source, 'antifreeze', 5)
ox_inventory:RemoveItem(source, 'sudo', 10)
end
```
</Tab>
</Tabs>
@@ -0,0 +1,16 @@
---
keywords: ['hasitem']
---
Get the total item count for all items in the player's inventory with the given name and metadata.
```lua
exports.ox_inventory:GetItemCount(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,7 @@
Get all items in the player's inventory.
```lua
exports.ox_inventory:GetPlayerItems()
```
**Returns:** `table`
@@ -0,0 +1,7 @@
Get the maximum carry weight of the player's inventory.
```lua
exports.ox_inventory:GetPlayerMaxWeight()
```
**Returns:** `number`
@@ -0,0 +1,7 @@
Get the total weight of all items in the player's inventory.
```lua
exports.ox_inventory:GetPlayerWeight()
```
**Returns:** `number`
@@ -0,0 +1,12 @@
Get a slot id in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,12 @@
Get all slot ids in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdsWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number[]?`
@@ -0,0 +1,12 @@
Get data for a slot in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table?`
@@ -0,0 +1,12 @@
Get data all slots in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotsWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table[]?`
@@ -0,0 +1,84 @@
---
keywords: ['hasitem']
---
import { Tabs, Tab } from 'nextra-theme-docs';
Searches the inventory for an item, or list of items, with the result varying based on the first argument.
```lua
exports.ox_inventory:Search(search, item, metadata)
```
* search: `'slots'` or `'count'`
* `'slots'` returns a table of slots where the item was found at.
* `'count'` returns the count of the specified item in player's inventory. If searching for multiple items
returns key-value pairs of itemName = count.
* item: `table` or `string`
* Can be a single item name or array of item names.
* metadata?: `table` or `string`
* If metadata is provided as a string it will search the item's `metadata.type` property.
### Count
<Tabs items={["Single item", "Multiple items"]}>
<Tab>
```lua
local count = exports.ox_inventory:Search('count', 'water')
print('You have '..count.. ' water')
```
</Tab>
<Tab>
```lua
local inventory = exports.ox_inventory:Search('count', {'meat', 'skin'}, {grade="1"})
if inventory then
for name, count in pairs(inventory) do
print('You have '..count..' '..name)
end
end
```
</Tab>
</Tabs>
### Slots
<Tabs items={["Single item", "Multiple items"]}>
<Tab>
```lua
local water = exports.ox_inventory:Search('slots', 'water')
local count = 0
for _, v in pairs(water) do
print(v.slot..' contains '..v.count..' water '..json.encode(v.metadata))
count = count + v.count
end
print('You have '..count..' water')
```
</Tab>
<Tab>
```lua
local items = exports.ox_inventory:Search('slots', {'meat', 'skin'}, 'deer')
if items then
for name, data in pairs(items) do
local count = 0
for _, v in pairs(data) do
if v.slot then
print(v.slot..' contains '..v.count..' '..name..' '..json.encode(v.metadata))
count = count + v.count
end
end
print('You have '..count..' '..name)
end
end
```
</Tab>
</Tabs>
@@ -0,0 +1,15 @@
Returns a table of all registered items. The format is as defined in [data/items.lua](https://github.com/overextended/ox_inventory/blob/main/data/items.lua).
```lua
exports.ox_inventory:Items()
```
The following snippet can be used in crafting resources such as okokCrafting or core_crafting, rather than retrieving information from the server.
```lua
local itemNames = {}
for item, data in pairs(exports.ox_inventory:Items()) do
itemNames[item] = data.label
end
```
@@ -0,0 +1,17 @@
---
title: invBusy
---
Returns whether the player's inventory is currently running an action (i.e. using an item)
* invBusy: `boolean`
```lua
local isInventoryBusy = LocalPlayer.state.invBusy
if isInventoryBusy then
-- Do stuff when busy
else
-- Do stuff when not busy
end
```
@@ -0,0 +1,15 @@
---
title: invHotkeys
---
Allows you to enable/disable a player's access to inventory hotkeys.
* invHotkeys: `boolean`
```lua
LocalPlayer.state.invHotkeys = false
```
```lua
LocalPlayer.state.invHotkeys = true
```
@@ -0,0 +1,16 @@
---
title: invOpen
---
Returns whether the player's inventory is currently open or not.
* invOpen: `boolean`
```lua
local isInventoryOpen = LocalPlayer.state.invOpen
if isInventoryOpen then
-- Do stuff when open
else
-- Do stuff when closed
end
@@ -0,0 +1,9 @@
Enables the weapon wheel, but disables the use of inventory items.
Mostly used for weaponised vehicles, though could be called for "minigames"
```lua
local exports.ox_inventory:weaponWheel(state)
```
* state: `boolean`
@@ -0,0 +1,5 @@
Closes the player's inventory.
```lua
exports.ox_inventory:closeInventory()
```
@@ -0,0 +1,24 @@
Sets a metadata property to display in the tooltip.
```lua
exports.ox_inventory:displayMetadata(metadata, value)
```
* metadata: `table` or `string`
* If metadata is a string then it's the metadata property you want to display, value is **not** optional then.
* Can be a table of key-value pairs, key being the metadata property and value being the label for that property.
* value?: `string`
* Label for the string metadata property to be displayed.
**Example:**
```lua
exports.ox_inventory:displayMetadata('mustard', 'Mustard')
```
```lua
exports.ox_inventory:displayMetadata({
mustard = 'Mustard',
ketchup = 'Ketchup'
})
```
@@ -0,0 +1,28 @@
Get data for the currently equipped weapon.
```lua
exports.ox_inventory:getCurrentWeapon()
```
You can also listen for changes to the current weapon using an event handler.
```lua
AddEventHandler('ox_inventory:currentWeapon', function(currentWeapon)
CurrentWeapon = currentWeapon
end)
```
- currentWeapon?: `table`
- ammo?: `string` Name of the item used as ammo.
- hash: `number`
- label: `string`
- melee: `boolean`
- metadata: `table`
- ammo?: `number` Amount of ammo loaded into the weapon.
- components?: `table` Array of component item names, used to apply weapon components.
- durability?: `number`
- registered?: `string` Name of the player that bought the weapon at a shop.
- serial?: `string`
- name: `string` Name of the item.
- slot: `number`
- weight: `number`
@@ -0,0 +1,61 @@
import { Tabs, Tab } from 'nextra-theme-docs';
Opens an inventory using the passed data.
```lua
exports.ox_inventory:openInventory(invType, data)
```
* invType: `string`
* `'player'`
* `'shop'`
* `'stash'`
* `'crafting'`
* `'container'`
* `'drop'`
* `'glovebox'`
* `'trunk'`
* `'dumpster'`
* data: `number` or `string` or `table`
<Tabs items={['Player', 'Shop', 'Stash']}>
<Tab>
**Open the target player's inventory.**
```lua
exports.ox_inventory:openInventory('player', 3)
```
</Tab>
<Tab>
**Open the fourth "General Store" [location](https://github.com/overextended/ox_inventory/blob/main/data/shops.lua#L14).**
```lua
exports.ox_inventory:openInventory('shop', { type = 'General', id = 4 })
```
</Tab>
<Tab>
**Open the first stash in [data/stashes](https://github.com/overextended/ox_inventory/blob/main/data/stashes.lua#L2-L19).**
```lua
exports.ox_inventory:openInventory('stash', 1)
```
**Open a custom stash (created on the server with RegisterStash).**
```lua
exports.ox_inventory:openInventory('stash', 'society_police')
```
**Open a stash with a specific owner.**
```lua
exports.ox_inventory:openInventory('stash', { id = 'police_locker', owner = 'license:xxxxxxxx' })
```
</Tab>
</Tabs>
@@ -0,0 +1,9 @@
If possible opens the nearby player's inventory.
The player trying to open the inventory must be able to open their own and
if the player does not have a police job, the target player must be fatally injured or
playing one of the death anims.
```lua
exports.ox_inventory:openNearbyInventory()
```
@@ -0,0 +1,15 @@
Forces the secondary-inventory key to open the passed inventory. Can be useful to enable inventory access while standing inside a marker.
```lua
exports.ox_inventory:setStashTarget(id, owner)
```
* id: `string` or `number`
* Stash id.
* owner?: `string` or `number`
**Example:**
```lua
exports.ox_inventory:setStashTarget('motel5', 'bobsmith')
```
@@ -0,0 +1,32 @@
Uses the passed item, then triggers the callback function.
Should be calling during item callbacks to utilise the builtin methods (server checks, progress bar, etc.).
```lua
exports.ox_inventory:useItem(data, cb)
```
* data: `table`
* cb?: `function`
```lua
exports('bandage', function(data, slot)
local playerPed = PlayerPedId()
local maxHealth = GetEntityMaxHealth(playerPed)
local health = GetEntityHealth(playerPed)
-- Does the ped need to heal?
if health < maxHealth then
-- Use the bandage
exports.ox_inventory:useItem(data, function(data)
-- The item has been used, so trigger the effects
if data then
SetEntityHealth(playerPed, math.min(maxHealth, math.floor(health + maxHealth / 16)))
lib.notify({description = 'You feel better already'})
end
end)
else
-- Don't use the item
lib.notify({type = 'error', description = 'You don\'t need a bandage right now'})
end
end)
```
@@ -0,0 +1,7 @@
Uses the item in the given inventory slot.
```lua
exports.ox_inventory:useSlot(slot)
```
* slot: `number`
@@ -0,0 +1,199 @@
# Event Hooks
Event hooks allow 3rd party resources to define new behaviour without modifying the inventory code directly.
## registerHook
```lua
exports.ox_inventory:registerHook(eventName, function(payload) end, options)
```
- eventName: `string`
- payload: `table`
- options?: `table`
- print?: `boolean`
- Print to the console when triggering the event.
- itemFilter?: `{ [string]: true }`
- The event will only trigger for items defined as keys in a set.
- inventoryFilter?: `string[]`
- The event will only trigger for inventories that match one of the [patterns](<http://www.easyuo.com/openeuo/wiki/index.php/Lua_Patterns_and_Captures_(Regular_Expressions)>) in the array.
- typeFilter?: `{ [string]: true }`
- The event will only trigger for inventories with one of the provided types (e.g. 'player', 'stash')
Return:
- hookId: `number`
### swapItems
Triggered when moving any item from one slot to another, or when "giving" an item.
By returning `false`, you can cancel the action and revert the inventory state.
**Payload:**
- source: `number`
- action: `'move'` or `'stack'` or `'swap'` or `'give'`
- fromInventory: `table` or `string` or `number`
- toInventory: `table` or `string` or `number`
- fromType: `string`
- toType: `string`
- fromSlot: `table`
- toSlot?: `table` or `number`
- count: `number`
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('swapItems', function(payload)
print(json.encode(payload, { indent = true }))
return false
end, {
print = true,
itemFilter = {
water = true,
},
inventoryFilter = {
'^glove[%w]+',
'^trunk[%w]+',
}
})
```
Blacklists "water" from being moved into or from gloveboxes and trunks.
### openInventory
**Payload:**
- source: `number`
- inventoryId: `number` or `string`
- inventoryType: `string`
Triggered when a player tries to open a secondary inventory.
By returning `false`, you can cancel the action and keep the player's inventory closed.
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('openInventory', function(payload)
print(json.encode(payload, { indent = true }))
return false
end, {
print = true,
inventoryFilter = {
'^glove[%w]+',
'^trunk[%w]+',
}
})
```
Disables gloveboxes and trunks.
### createItem
**Payload:**
- inventoryId?: `number` or `string`
- metadata: `table`
- item: `table`
- count: `number`
Triggered when an item is created, either by buying it, using AddItem, or when converting inventory data.
By returning a table you can modify or replace the metadata given to an item.
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('createItem', function(payload)
print(json.encode(payload, { indent = true }))
local metadata = payload.metadata
metadata.label = 'Mineral Water'
return metadata
end, {
print = true,
itemFilter = {
water = true
}
})
```
Sets the label for "water" to "Mineral Water".
### buyItem
**Payload:**
- source: `number`
- shopType: `string`
- shopId: `number`
- toInventory: `number`
- toSlot: `number`
- itemName: `string`
- metadata: `table`
- count: `number`
- price: `number`
- totalPrice: `number`
- currency?: `string`
Triggered when an item is about to be purchased and can return `false` to prevent the transaction.
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('buyItem', function(payload)
print(json.encode(payload, { indent = true, sort_keys = true }))
return false
end, {
print = true,
itemFilter = {
water = true
},
})
```
Prevents players from purchasing items at General stores.
### craftItem
**Payload:**
- source: `number`
- benchId: `number`
- benchIndex: `number`
- recipe: `table`
- count: `number`
- duration: `number`
- ingredients: `table<string, number>`
- name: `string`
- slot: `number`
- weight: `number`
- toInventory: `number`
- toSlot: `number`
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('craftItem', function(payload)
print(json.encode(payload, { indent = true, sort_keys = true }))
return false
end, {
print = true,
itemFilter = {
lockpick = true
},
})
```
Prevent lockpicks from being crafted by players.
## removeHooks
```lua
exports.ox_inventory:removeHooks(id)
```
- id?: `number`
Removes a hook created by the invoking resource with the the specified id.
If no id is specified then all hooks registered by the resource are removed.
@@ -0,0 +1,57 @@
Adds an item into the specified inventory.
Should be used alongside [CanCarryItem](./CanCarryItem.md) otherwise, the maximum weight may be exceeded.
```lua
exports.ox_inventory:AddItem(inv, item, count, metadata, slot, cb)
```
- inv: `table` or `string` or `number`
- The inventory's unique id, or a table with the id and owner.
- playerId: `1`
- inventoryId: `gloveVGH283`
- `{ id = 'personallocker', owner = 'license:xxxxxx'}`
- item: `string`
- The name of the item to add to the target.
- count: `number`
- The number of items to add.
- metadata?: `table` or `string`
- A table of unique data to attach to the item object. A string will create a table with the "type" field.
- slot?: `number`
- A specific slot to add the item to. If the slot is invalid, the first available slot will be used instead.
- cb?: function(success: `boolean`, response?: `string`)
If used for glovebox, trunk or stash you must first check the inventory is loaded with [GetInventory](./GetInventory.md)
Returns `success, response` if cb is undefined, otherwise they are used in the callback only.
**Example:**
```lua
local success, response = exports.ox_inventory:AddItem('gloveVGH283', 'bread', 4)
if not success then
-- if no slots are available, the value will be "inventory_full"
return print(response)
end
print(json.encode(response, {indent=true}))
--[[
{
"metadata": [],
"label": "Bread",
"slot": 1,
"stack": true,
"close": true,
"name": "bread",
"count": 1,
"weight": 150
}
]]
```
**Possible value of the "response" argument, on failure:**
- "invalid_item": the item doesn't exist
- "invalid_inventory": the inventory doesn't exist
- "inventory_full": no free slots
@@ -0,0 +1,18 @@
Returns the amount a player can hold based on available weight.
```lua
exports.ox_inventory:CanCarryAmount(inv, item)
```
* inv: `table` or `string` or `number`
* item: `table` or `string`
* Can be array to check multiple items.
Example:
```lua
-- Checks how much you can carry
amountToAdd = exports.ox_inventory:CanCarryAmount(inv, 'stone')
-- Adds the amount
exports.ox_inventory:AddItem(inv, 'stone', amountToAdd)
```
@@ -0,0 +1,25 @@
Returns true or false depending if the inventory can carry the specified item.
The function checks for inventory weight and available slots.
```lua
exports.ox_inventory:CanCarryItem(inv, item, count, metadata)
```
* inv: `table` or `string` or `number`
* item `table` or `string`
* Can be array of items.
* count: `number`
* metadata?: `table` or `string`
* If metadata is passed as string then `metadata.type` will be checked.
**Example:**
```lua
-- Checks if the player calling the event can carry 3 water items
if exports.ox_inventory:CanCarryItem(source, 'water', 3) then
-- Do stuff if can carry
else
-- Do stuff if can't carry
end
```
@@ -0,0 +1,26 @@
Returns if inventory can carry specified weight and free inventory weight.
```lua
exports.ox_inventory:CanCarryWeight(inv, weight)
```
* inv: `table` or `string` or `number`
* weight: `number`
Example:
```lua
-- Checks if player can carry 1000 grams.
local fillAmount = 1000
local canCarryWeight, freeWeight = ox_inventory:CanCarryWeight(playerId, fillAmount)
if freeWeight == 0 then
-- Player can't carry weight.
return
elseif not canCarryWeight then
-- Modify fillAmount, because inventory can't carry specified weight
fillAmount = freeWeight
end
-- Do something
```
@@ -0,0 +1,11 @@
Returns true if the item swap is possible based on inventory weight.
```lua
exports.ox_inventory:CanSwapItem(inv, firstItem, firstItemCount, testItem, testItemCount)
```
* inv: `table` or `string` or `number`
* firstItem: `string`
* firstItemCount: `number`
* testItem: `string`
* testItemCount: `number`
@@ -0,0 +1,8 @@
Clears the specified inventory. The `keep` argument is either a string or an array of strings containing the name(s) of the item(s) to keep in the inventory after clearing.
```lua
exports.ox_inventory:ClearInventory(inv, keep)
```
* inv: `table` or `string` or `number`
* keep?: `string` or `string[]`
@@ -0,0 +1,10 @@
Clears a player's inventory and saves it to a stash.
Use [ReturnInventory](./ReturnInventory.md) to return the confiscated inventory back to
the player.
```lua
exports.ox_inventory:ConfiscateInventory(source)
```
* source: `number`
@@ -0,0 +1,16 @@
Takes traditional item data and updates it to support ox_inventory.
```lua
exports.ox_inventory:ConvertItems(playerId, items)
```
* playerId: `number`
* items: `table`
Data conversion example:
```lua
Old: [{"cola":1, "bread":3}]
New: [{"slot":1,"name":"cola","count":1},
{"slot":2,"name":"bread","count":3}]
```
@@ -0,0 +1,18 @@
# CreateDropFromPlayer
Creates a new drop with the contents of a player's inventory.
```lua
exports.ox_inventory:CreateDropFromPlayer(playerId)
```
- playerId: `number`
Return:
- dropId: `string`
**Example**
```lua
local dropId = exports.ox_inventory:CreateDropFromPlayer(1)
```
@@ -0,0 +1,43 @@
# CreateTemporaryStash
Creates a temporary stash which will be removed after some time.
```lua
exports.ox_inventory:CreateTemporaryStash(properties)
```
- properties: `table`
- label: `string`
- slots: `number`
- maxWeight: `number`
- owner?: `string` `number` or `boolean`
- `string`: Can only access the stash linked to the owner.
- `true`: Each player has a unique stash but can request other player's stashes.
- The inventory is always shared if `false` or `nil`.
- groups?: `table<string, number>`
- Table of group names (e.g. jobs) where the numeric value is the minimum grade required.
- `{['police'] = 0, ['ambulance'] = 2}`
- coords?: `vector3`
- Stash can only be accessed while nearby.
- items?: `{ [number]: string, [number]: number, [number]?: table }[]`
- An array of tables, containing a sequence of itemName, count, metadata.
Return:
- inventoryId: `string`
**Example**
```lua
local mystash = exports.ox_inventory:CreateTemporaryStash({
label = 'mystash',
slots = 5,
maxWeight = 5000,
items = {
{ 'WEAPON_MINISMG', 1 },
{ 'ammo-9', 69 },
{ 'water', 2, { label = 'Mineral water' } }
}
})
TriggerClientEvent('ox_inventory:openInventory', 1, 'stash', mystash)
```
@@ -0,0 +1,30 @@
Drops can be created from other resources, containing a variety of items and utilising a custom label (instead of 'Drop 32648').
```lua
exports.ox_inventory:CustomDrop(prefix, items, coords, slots, maxWeight, instance, model)
```
- prefix: `string`
- items: `table`
- name: `string`
- count: `number`
- metadata?: `table`
- coords: `vector3`
- slots?: `number`
- maxWeight?: `number`
- instance?: `string` or `number`
- model?: `number`
```lua
-- Create a generic drop with a marker
exports.ox_inventory:CustomDrop('Carcass', {
{'meat', 5, { grade = 2, type = 'deer' }},
{'hide', 5, { grade = 2, type = 'deer' }}
}, coords)
-- Create a drop with an entity
exports.ox_inventory:CustomDrop('SMG', {
{ 'WEAPON_MINISMG', 1 },
{ 'ammo-9', 69 },
}, GetEntityCoords(GetPlayerPed(1)), 5, 10000, nil, `w_sb_minismg`)
```
@@ -0,0 +1,10 @@
Returns the inventory associated with the container linked in the slot of the given inventory.
```lua
exports.ox_inventory:GetContainerFromSlot(inv, slotId)
```
- inv: `table` or `string` or `number`
- slotId: `number`
**Returns:** `table?`
@@ -0,0 +1,8 @@
Returns the player's currently equipped weapon as a table.
```lua
-- inv: string or number
exports.ox_inventory:GetCurrentWeapon(inv)
```
* inv: `table` or `string` or `number`
@@ -0,0 +1,9 @@
Get the first available empty slot in an inventory.
```lua
exports.ox_inventory:GetEmptySlot(inv)
```
- inv: `table` or `string` or `number`
**Returns:** `number?`
@@ -0,0 +1,27 @@
Returns the inventory associated with the ID (and owner if defined). Otherwise returns null.
```lua
exports.ox_inventory:GetInventory(inv, owner)
```
* inv: `number` or `table`
* owner?: `string` or `boolean`
**Example:**
```lua
local inventory = exports.ox_inventory:GetInventory('example_stash', false)
print(json.encode(inventory, {indent = true}))
--[[
{
"id": "example_stash,
"label": "Police Stash",
"type": "stash,
"slots": 50,
"weight": 0,
"maxWeight": 100000,
"owner": false,
...
}
]]
```
@@ -0,0 +1,14 @@
Returns all slots with items in a inventory.
```lua
exports.ox_inventory:GetInventoryItems(inv, owner)
```
* inv: `number` or `table`
* owner?: `string` or `boolean`
**Example:**
```lua
local playerItems = exports.ox_inventory:GetInventoryItems(source)
```
@@ -0,0 +1,36 @@
Returns _generic_ item data from the specified inventory, with the total count.
```lua
exports.ox_inventory:GetItem(inv, item, metadata, returnsCount)
```
* inv: `table` or `string` or `number`
* item: `table` or `string`
* Can be items array.
* metadata?: `any`
* Only returns the count of items that strictly match the given metadata.
* returnsCount?: `boolean`
If `returnsCount` is set to true, the returned value will be the `count` based on
how many times the item was found.
Otherwise returns the data related to the item _and_ its total count found in the inventory.
**Example**:
```lua
local item = ox_inventory:GetItem(source, 'water', nil, false)
print(json.encode(item, {indent=true}))
--[[
{
"consume": 1,
"count": 15,
"stack": true,
"name": "water",
"weight": 500,
"label": "Water",
"close": true
}
]]
```
@@ -0,0 +1,13 @@
Get the total item count for all items in an inventory with the given name and metadata.
```lua
exports.ox_inventory:GetItemCount(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,9 @@
Returns the number of slots the specified item is in, the item's total count and the remaining empty slots.
```lua
exports.ox_inventory:GetItemSlots(inv, item, metadata)
```
* inv: `table` or `string` or `number`
* item: `table` or `string`
* metadata?: `table`
@@ -0,0 +1,29 @@
Returns the specified slot data as a table.
```lua
exports.ox_inventory:GetSlot(inv, slot)
```
* inv: `table` or `string` or `number`
* slot: `number`
**Example:**
```lua
local slot = exports.ox_inventory:GetSlot(source, 1)
print(json.encode(slot, {indent=true}))
--[[
{
"weight": 2000,
"name": "water",
"metadata": [],
"slot": 1,
"label": "Water",
"close": true,
"stack": true,
"count: 4
}
]]
```
@@ -0,0 +1,11 @@
Get the slot id of an existing item matching the given data, or an empty slot.
```lua
exports.ox_inventory:GetSlotForItem(inv, itemName, metadata)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata: `table?`
**Returns:** `number?`
@@ -0,0 +1,13 @@
Get a slot id in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,13 @@
Get all slot ids in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdsWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number[]?`
@@ -0,0 +1,13 @@
Get data for a slot in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table?`
@@ -0,0 +1,13 @@
Get data all slots in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotsWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table[]?`
@@ -0,0 +1,33 @@
import { Callout } from 'nextra/components';
Creates a new custom stash.
```lua
exports.ox_inventory:RegisterStash(id, label, slots, maxWeight, owner, groups, coords)
```
- id: `string` or `number`
- Stash identifier when loading from the database.
- label: `string`
- Display name when inventory is open.
- slots: `number`
- maxWeight: `number`
- owner: `string` or `boolean` or `nil`
- `string`: Can only access the stash linked to the owner.
- `true`: Each player has a unique stash but can request other player's stashes.
- `nil`: Always shared.
- groups: `table`
- Table of player groups (jobs) able to access the stash.
- Table of group names where the numeric value is the minimum grade required.
- `{['police'] = 0, ['ambulance'] = 2}`
- coords?: `vector3` or `vector3[]`
<Callout>
This function needs to be triggered before a player can open the stash.
</Callout>
**Example:**
For a use case example on this function check out the written [Guide](../../../Guides/stashes.md) for it.
@@ -0,0 +1,35 @@
Removes the specified item from the specified inventory.
```lua
exports.ox_inventory:RemoveItem(inv, item, count, metadata, slot)
```
- inv: `table` or `string` or `number`
- The inventory's unique id, or a table with the id and owner.
- playerId: `1`
- inventoryId: `gloveVGH283`
- `{ id = 'personallocker', owner = 'license:xxxxxx'}`
- item: `string`
- The name of the item to remove from the target.
- count: `number`
- The number of items to remove.
- metadata?: `table` or `string`
- Only remove items with matching metadata properties.
- slot?: `number`
- A specific slot to remove the item from. If the slot is invalid, the first available slot will be used instead.
- cb?: function(success: `boolean`, response?: `string`)
Returns success: `boolean`, response: `string?`.
**Possible value of "response" on failure:**
- "invalid_item": the item doesn't exist
- "invalid_inventory": the inventory doesn't exist
- "not_enough_items": inventory did not contain enough of the given item
**Example:**
```lua
-- Removes 2 water from the glovebox for the given plate.
local success = exports.ox_inventory:RemoveItem('gloveVGH283', 'water', 2)
```
@@ -0,0 +1,9 @@
Returns the confiscated inventory back to the player.
Use it alongside [ConfiscateInventory](./ConfiscateInventory.md).
```lua
exports.ox_inventory:ReturnInventory(source)
```
* source: `number`
@@ -0,0 +1,13 @@
Searches an inventory for a specified item.
```lua
exports.ox_inventory:Search(inv, search, item, metadata)
```
* inv: `table` or `string` or `number`
* search: `string`
* item: `table` or `string`
* metadata?: `table` or `string`
`search` can be either `'slots'` or `'count'`, where slots will return a table of data
and count will return the found amount of the specified item.
@@ -0,0 +1,27 @@
Sets durability onto the specified slot.
Can be used for repairing weapons.
```lua
exports.ox_inventory:SetDurability(inv, slot, durability)
```
* inv: `table` or `string` or `number`
* slot: `number`
* durability: `number`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
-- Set the durability of the item in slot 3 of source player's inventory to 100
ox_inventory:SetDurability(source, 3, 100)
-- Set the durability of the source player's current weapon to 100
local weapon = ox_inventory:GetCurrentWeapon(source)
if weapon then
ox_inventory:SetDurability(source, weapon.slot, 100)
end
```
@@ -0,0 +1,17 @@
Sets the maximum weight available for an inventory.
```lua
exports.ox_inventory:SetMaxWeight(inv, maxWeight)
```
* inv: `table` or `string` or `number`
* maxWeight: `number`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
-- Set the max weight for player 1's inventory to 20kg.
ox_inventory:SetMaxWeight(1, 20000)
```
@@ -0,0 +1,27 @@
Sets metadata on the specified slot.
```lua
ox_inventory:SetMetadata(inv, slot, metadata)
```
* inv: `table` or `string` or `number`
* slot: `number`
* metadata: `table`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
local water = ox_inventory:Search(source, 1, 'water')
for k, v in pairs(water) do
print('\n______________'..'\n- index '..k)
print(v.name, 'slot: '..v.slot, 'metadata: '..json.encode(v.metadata))
water = v
break
end
water.metadata.type = 'clean'
ox_inventory:SetMetadata(source, water.slot, water.metadata)
print(('modified %sx water in slot %s with new metadata'):format(water.count, water.slot))
```
@@ -0,0 +1,17 @@
Sets the number of slots available for an inventory.
```lua
exports.ox_inventory:SetSlotCount(inv, slots)
```
* inv: `table` or `string` or `number`
* slots: `number`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
-- Set the slot count for player 1's inventory to 10.
ox_inventory:SetSlotCount(1, 10)
```
@@ -0,0 +1,10 @@
Swaps slots in specified inventories.
```lua
exports.ox_inventory:SwapSlots(fromInventory, toInventory, slot1, slot2)
```
* fromInventory: `table` or `string` or `number`
* toInventory: `table` or `string` or `number`
* slot1: `number`
* slot2: `number`
@@ -0,0 +1,20 @@
Returns a table of all registered items. The format is as defined in [data/items.lua](https://github.com/overextended/ox_inventory/blob/main/data/items.lua).
```lua
exports.ox_inventory:Items()
```
The following snippet can be used in crafting resources such as okokCrafting or core_crafting, rather than querying the database.
```lua
local itemNames
ESX.RegisterServerCallback('crafting:itemNames', function(source, cb)
if not itemNames then
itemNames = {}
for item, data in pairs(exports.ox_inventory:Items()) do
itemNames[item] = data.label
end
end
cb(itemNames)
end)
```
@@ -0,0 +1,10 @@
# UpdateVehicle
Update the internal reference to vehicle stashes, without triggering a save or updating the database.
```lua
exports.ox_inventory:UpdateVehicle(oldPlate, newPlate)
```
* oldPlate: `string`
* newPlate: `string`
@@ -0,0 +1,60 @@
import { Tabs, Tab } from 'nextra-theme-docs';
Opens an inventory using the passed data.
Forces a player to open an inventory, without usual security checks (groups, coords).
```lua
exports.ox_inventory:forceOpenInventory(playerId, invType, data)
```
- playerId: `number`
- invType: `string`
- `'player'`
- `'stash'`
- `'container'`
- `'drop'`
- `'glovebox'`
- `'trunk'`
- `'dumpster'`
- data: `number` or `string` or `table`
<Tabs items={["Player", "Stash"]}>
<Tab>
**Open the target player's inventory.**
```lua
exports.ox_inventory:forceOpenInventory(1, 'player', 3)
```
**Admin command to open a player's inventory.**
```lua
RegisterCommand('openplayerinv', function(source, args)
exports.ox_inventory:forceOpenInventory(source, 'player', tonumber(args[1]))
end, true)
```
</Tab>
<Tab>
**Open the first stash in [data/stashes](https://github.com/overextended/ox_inventory/blob/main/data/stashes.lua#L2-L19).**
```lua
exports.ox_inventory:forceOpenInventory(1, 'stash', 'apartment420')
```
**Open a custom stash (created on the server with RegisterStash).**
```lua
exports.ox_inventory:forceOpenInventory(1, 'stash', 'society_police')
```
**Open a stash with a specific owner.**
```lua
exports.ox_inventory:forceOpenInventory(1, 'stash', { id = 'police_locker', owner = 'license:xxxxxxxx' })
```
</Tab>
</Tabs>
@@ -0,0 +1,15 @@
Creates and sets the player's inventory.
```lua
exports.ox_inventory:setPlayerInventory(player, data)
```
* player: `table`
* source: `number`
* identifier: `string`
* name: `string`
* groups?: `table`
* sex?: `string`
* dateofbirth?: `string`
* data?: `table`
* If not provided will load player's inventory data from the db.
+74
View File
@@ -0,0 +1,74 @@
---
title: Creating crafting points
---
Crafting locations, items and their ingredients are defined in [data/crafting.lua](https://github.com/overextended/ox_inventory/blob/main/data/crafting.lua).
## Crafting definition
```lua
{
items = {
{
name = 'lockpick',
ingredients = {
garbage = 3,
WEAPON_HAMMER = 0.1
},
duration = 5000,
count = 3,
metadata = { durability = 20 }
},
{
name = 'garbage',
ingredients = {
cola = 1
},
metadata = { description = 'An empty soda can.', weight = 20, image = 'trash_can' }
},
},
points = {
vec3(-1147.083008, -2002.662109, 13.180260),
},
zones = {
{
coords = vec3(-1146.2, -2002.05, 13.2),
size = vec3(3.8, 1.05, 0.15),
distance = 1.5,
rotation = 315.0,
},
},
blip = { id = 566, colour = 31, scale = 0.8 },
},
```
* items: `table`
* name: `string`
* ingredients: `table`
* Item ingredients can be seen in the item tooltip.
* Key-value pairs of item name and consume count
* key - Item name.
* value - If 1 or above it's the consume count, if below 1 and above 0 it's the durability consume amount, if
set to 0 then the item is required but not consumed.
* duration: `number`
* Crafting duration in milliseconds.
* count: `number`
* Item amount received upon crafting.
* metadata: `table`
* Metadata applied to the item being crafted.
* points: `vector3[]`
* Interaction locations that will open the crafting inventory.
* groups: `table`
* Key-value pairs of job name and minimum grade to access the crafting location.
* `{["police"] = 0, ["ambulance"] = 2}`
* zones: `table`
* ox_lib targeting zones used for ox_target.
* coords: `vector3`
* size: `vector3`
* distance: `number`
* rotation: `number`
* blip: `table`
* id: `number`
* Blip sprite number.
* colour: `number`
* scale: `number`
+265
View File
@@ -0,0 +1,265 @@
---
title: Creating items
---
import { Tabs, Tab } from 'nextra-theme-docs';
## Defining item data
Before being able to see or use an item in game it **must** first be defined.
All of the items are defined in the `/data/items.lua` file with key, value pairs.
Key is the name (not the label) of an item and the value is a table containing the
options for the item.
**Item options:**
* label: `string`
* weight?: `number`
* stack?: `boolean`
* If set to false will not allow the item to be stacked.
* degrade?: `number`
* Amount of time in minutes the item will degrade after.
* close?: `boolean`
* If set to false does not close the inventory on item use.
* description?: `string`
* Item description that will be shown in the tooltip
* consume?: `number`
* Item count needed and removed use.
* Default: 1
* If set to a decimal will consume durability instead (0.2 = 20%).
* allowArmed?: `boolean`
* If set to true will allow use of item while armed with a weapon.
* server?: `table`
* export?: `string`
* client?: `table`
* export?: `string`
* Export to be triggered after item use.
* event?: `string`
* Event to be triggered after item use.
* status?: `table`
* Adjust esx_status values after use.
* anim?: `table`
* Animation that will be played during the progress bar.
* dict: `string`
* clip: `string`
* prop?: `table`
* Attached prop that will be displayed during the progress bar.
* model: `string` or `hash`
* pos: `table` (x, y, z)
* rot: `table` (x, y, z)
* disable?: `table`
* Actions to be disabled during the progress bar
* move?: `boolean`
* car?: `boolean`
* combat?: `boolean`
* mouse?: `boolean`
* usetime?: `number`
* cancel?: `boolean`
* If set to true the player canc cancel item use.
* add?: `function`(total: `number`)
* Function that triggers when receiving an item
* Returns total item count as `total`
* remove?: `function`(total: `number`)
* Function that triggers when removing an item
* Returns total item count as `total`
* buttons?: `table`
* label: `string`
* action: `function`(slot: `number`)
* Callback function when button is clicked in context menu, returns item slot.
**Examples:**
<Tabs items={["Burger", "Burger with description", "Burger with notification"]}>
<Tab>
```lua
['burger'] = {
label = 'Burger',
weight = 220,
stack = true,
close = true,
client = {
status = { hunger = 200000 },
anim = { dict = 'mp_player_inteat@burger', clip = 'mp_player_int_eat_burger_fp' },
prop = {
model = 'prop_cs_burger_01',
pos = { x = 0.02, y = 0.02, y = -0.02},
rot = { x = 0.0, y = 0.0, y = 0.0}
},
usetime = 2500,
}
}
```
</Tab>
<Tab>
A modified burger item which includes a description.
```lua
['burger'] = {
label = 'Burger',
description = 'Just what is the secret formula?'
weight = 220,
stack = true,
close = true,
client = {
status = { hunger = 200000 },
anim = { dict = 'mp_player_inteat@burger', clip = 'mp_player_int_eat_burger_fp' },
prop = {
model = 'prop_cs_burger_01',
pos = { x = 0.02, y = 0.02, y = -0.02},
rot = { x = 0.0, y = 0.0, y = 0.0}
},
usetime = 2500,
}
}
```
</Tab>
<Tab>
A modified burger item, which gives you notifications on add and remove arguments.
```lua
['burger'] = {
label = 'Burger',
weight = 220,
stack = true,
consume = 0,
client = {
add = function(total)
if total > 0 then
lib.notify({description = 'Nice burger you got there!'})
end
end,
remove = function(total)
if total < 1 then
lib.notify({description = 'You lost all of your burgers!'})
end
end
}
}
```
</Tab>
</Tabs>
## Making the item usable
* If you are using ESX, you can continue using `ESX.RegisterUsableItem`.
* If you are using QBCore, you can continue using `QBCore.Functions.CreateUseableItem`.
Using the built-in system is more secure and provides much more functionality.
### Client callbacks
Item callbacks can be added by defining an export (recommended), or by adding it to [items/client.lua](https://github.com/overextended/ox_inventory/blob/main/modules/items/client.lua#L33).
When defining [item data](https://github.com/overextended/ox_inventory/blob/main/data/items.lua#L11), adding client.export will trigger an event on item use.
The correct formatting is `export = resourceName.exportName`.
```lua
exports('bandage', function(data, slot)
local playerPed = PlayerPedId()
local maxHealth = GetEntityMaxHealth(playerPed)
local health = GetEntityHealth(playerPed)
-- Does the ped need to heal? We can cancel the item from being used.
if health < maxHealth then
-- Triggers internal-code to correctly use items.
-- This adds security, removes the item on use, adds progressbar support, and is necessary for server callbacks.
exports.ox_inventory:useItem(data, function(data)
-- The server has verified the item can be used.
if data then
SetEntityHealth(playerPed, math.min(maxHealth, math.floor(health + maxHealth / 16)))
lib.notify({description = 'You feel better already'})
end
end)
else
-- Don't use the item
lib.notify({type = 'error', description = 'You don\'t need a bandage right now'})
end
end)
```
### Server callbacks
A callback function can be defined on the server to handle several events (usingItem, usedItem, buyItem).
This can either be an export (recommended), or added to the bottom of [items/server.lua](https://github.com/overextended/ox_inventory/blob/main/modules/items/server.lua).
When defining [item data](https://github.com/overextended/ox_inventory/blob/main/data/items.lua#L14), adding server.export will trigger an event for the actions above.
The correct formatting is `export = resourceName.exportName`.
```lua
exports('bandage', function(event, item, inventory, slot, data)
-- Player is attempting to use the item.
if event == 'usingItem' then
local playerPed = GetPlayerPed(inventory.id)
local maxHealth = GetEntityMaxHealth(playerPed)
local health = GetEntityHealth(playerPed)
-- Check if the player needs to be healed.
if health >= maxHealth then
TriggerClientEvent('ox_lib:notify', inventory.id, {type = 'error', description = 'You don\'t need a bandage right now'})
-- Returning 'false' will prevent the item from being used
return false
end
return
end
-- Player has finished using the item.
if event == 'usedItem' then
return TriggerClientEvent('ox_lib:notify', inventory.id, {description = 'You feel better already'})
end
-- Player is attempting to purchase the item.
if event == 'buying' then
return TriggerClientEvent('ox_lib:notify', inventory.id, {type = 'success', description = 'You bought a bandage'})
end
end)
```
## Creating container items
Like with other items the item must first be registered.
**Example:**
```lua
['paperbag'] = {
label = 'Paper Bag',
weight = 1,
stack = false,
close = false,
consume = 0
},
```
When registered you can define the item as a container in `/modules/items/containers.lua`
The key for the container is the `name` you gave it when registering the item.
You can also define the number of slots, the maximum weight, blacklist and whitelist items.
* itemName:
* slots: number
* The number represents the amount of slots
* maxWeight: number
* The number represents the maximum weight within the container
* blacklist:
* Supports single and multiple items
* `{ 'testburger', 'testburger2' }`
* whitelist:
* Supports single and multiple items
* `{ 'testburger', 'testburger2' }`
**Example:**
```lua
setContainerProperties('paperbag', {
slots = 5,
maxWeight = 1000,
blacklist = { 'testburger' }
})
```
+104
View File
@@ -0,0 +1,104 @@
---
title: Creating shops
---
Builtin shops are defined in [data/shops.lua](https://github.com/overextended/ox_inventory/blob/main/data/shops.lua), and more can be added here to benefit from the built-in markers or zones support.
## Shop definition
```lua
{
General = {
name = 'Shop',
blip = {
id = 59,
colour = 69,
scale = 0.8
},
inventory = {
{ name = 'burger', price = 10 },
{ name = 'water', price = 10 },
{ name = 'cola', price = 10 },
},
locations = {
vec3(25.7, -1347.3, 29.49),
},
targets = {
-- Shop using a BoxZone
{
loc = vec3(25.06, -1347.32, 29.5),
length = 0.7,
width = 0.5,
heading = 0.0,
minZ = 29.5,
maxZ = 29.9,
distance = 1.5
},
-- Shop using a ped
{
ped = `mp_m_shopkeep_01`,
scenario = 'WORLD_HUMAN_AA_COFFEE',
loc = vec3(24.407, -1347.283, 28.497),
heading = 270.311,
},
}
}
}
```
- name: `string`
- The label to display when the shop is open.
- blip?: `table`
- Creates a blip with the given settings. Leave it undefined for no blip to be created.
- id: `number`
- colour: `number`
- scale: `number`
- groups?: `table`
- Key-value pairs of job name and minimum grade to access the shop.
- `{["police"] = 0, ["ambulance"] = 2}`
- inventory: `table`
- name: `string`
- price: `number`
- currency?: `string`
- Item to be used as currency.
- count?: `number`
- Amount of the item in the stock.
- license?: `string`
- License required to purchase the item.
- metadata?: `table`
- grade?: `number` | `number[]`
- Grade required to purchase the item.
- locations?: `vector3[]`
- An array of coordinates to create unique instances of the shop archetype at, using markers.
- targets?: `table[]`
- An array of target settings to create unique instances of the shop archetype at, using peds or BoxZones (PolyZone data structure).
- model?: `number[]`
- An array of models that can be targetted to open a shop. Used for vending machines.
Targets and model are only available when using a targeting resource like ox_target.
## Register during runtime
Shops can be added using `exports.ox_inventory:RegisterShop` on the server, however they cannot utilise any client-only features.
- Blips, markers, and zones will not be created.
- Must use "locations" and not "targets" to define each shop using the archetype.
**Example:**
```lua
exports.ox_inventory:RegisterShop('TestShop', {
name = 'Test shop',
inventory = {
{ name = 'burger', price = 10 },
{ name = 'water', price = 10 },
{ name = 'cola', price = 10 },
},
locations = {
vec3(223.832962, -792.619751, 30.695190),
},
groups = {
police = 0
},
})
```
+88
View File
@@ -0,0 +1,88 @@
---
title: Creating custom stashes
---
import { GhButton } from '@components/button';
We can set up custom stashes from outside the resource utilising the exported RegisterStash function.
Firstly, we need to define the stashes properties.
### Stash properties
- id: `string`
- Unique name to identify the stash in the database.
- label: `string`
- Display name when viewing the stash.
- slots: `number`
- Number of slots the stash will have.
- weight: `number`
- Maximum weight of the stash inventory.
- owner?: `string` or `boolean`
- `true`: Each player has their own unique stash, but can request to open the stash of another player
- `false`: Only a single stash exists and is shared between all players
- `string`: The stash explicitly belongs to the given owner, usually a player identifier
- groups?: `table`
- Key-value pairs of job name and minimum grade to be able to access the stash. (`{["police"] = 0, ["ambulance"] = 2}`)
- name: `string`
- grade: `number`
- coords?: `vector3` or `table`
- You can set the stash coordinates to prevent the stash from being opened if the player isn't close enough.
- Vector or table containing the coordinates of the stash.
## Example
Below the value is hardset, but it could be loaded from the database (especially if there are unknown fields, i.e. owner)
```lua
-- Server
local stash = {
id = '42wallabyway',
label = '42 Wallaby Way',
slots = 50,
weight = 100000,
owner = 'char1:license'
}
AddEventHandler('onServerResourceStart', function(resourceName)
if resourceName == 'ox_inventory' or resourceName == GetCurrentResourceName() then
exports.ox_inventory:RegisterStash(stash.id, stash.label, stash.slots, stash.weight, stash.owner)
end
end)
-- Client
exports.ox_inventory:openInventory('stash', {id='42wallabyway', owner=property.owner})
```
The following sample is based on esx_property's db data.
```lua
-- Server
local properties
MySQL.query('SELECT * FROM `properties`', {}, function(result)
properties = result
end
RegisterNetEvent('ox:loadStashes', function(id)
local stash = properties[id]
if stash then
-- id: 1, name: WhispymoundDrive, label: 2677 Whispymound Drive, coords: {"x":118.748,"y":566.573,"z":175.697}
ox_inventory:RegisterStash(stash.name, stash.label, 50, 100000, true, false, json.encode(stash.room_menu))
end
end)
-- Client
local ox_inventory = exports.ox_inventory
if ox_inventory:openInventory('stash', property.id) == false then
TriggerServerEvent('ox:loadStashes')
ox_inventory:openInventory('stash', property.id)
end
```
## Example resource
We put together an example resource showcasing how to properly utilise the stash API:
<GhButton link="https://www.github.com/overextended/ox_inventory_examples" />
+6
View File
@@ -0,0 +1,6 @@
label: Ox Inventory
collapsible: true
collapsed: true
link:
type: generated-index
description: An slot-based inventory with item metadata for "item uniqueness".
+29
View File
@@ -0,0 +1,29 @@
---
title: Common issues
---
## UI has not been built
Because the UI for inventory is written in React it can't run natively under FiveM so it must first be bundled into html/css/js.
We provide an easy way for you to do this by downloading a pre-bundled release, which you can get from [here](https://github.com/overextended/ox_inventory/releases/latest).
Make sure you download the `ox_inventory.zip` file as that one contains the bundled files and others are raw source code.
If in case you wanted to edit the inventory UI you would have to build these files yourself.
To do so please read our [_Building inventory UI_](../Guides/inventory_ui.md) guide.
## No such export * in resource ox_inventory
There are several likely causes for this "issue".
- An error occurred while starting ox_inventory or one of its dependencies (e.g. ox_lib).
- The resource trying to use the export (e.g. esx_addoninventory) is being started _before_ ox_inventory.
- You're literally trying to call an export that does not exist, which is a you issue.
## Stashes / trunks are not saved at server restart
Stopping a server or "restarting" it does not trigger any events or allow for saving.
- Inventories are saved at a 5 minute interval.
- txAdmin scheduled restarts and shutdowns will trigger a save.
- The `saveinv` command can be used manually or triggered in the console.
- All inventories are saved when the number of online players hits 0.