================ CODE SNIPPETS ================ ### Configuring Server Startup Order (server.cfg) Source: https://github.com/4timci4/ox_lib-docs/blob/main/guides/getting-started.md This snippet demonstrates how to add `ensure ox_lib` to your server.cfg file. It is crucial to place this line before any other resource that depends on ox_lib to guarantee it loads first. ```cfg # Example server.cfg ensure ox_lib ensure your_other_resource ensure another_resource_using_oxlib ``` -------------------------------- ### Declaring Resource Dependencies and Loading ox_lib (fxmanifest.lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/guides/getting-started.md This fxmanifest.lua snippet shows how to declare ox_lib as a dependency using `dependencies { 'ox_lib' }` and how to load ox_lib's utility functions into your resource's environment using `shared_script '@ox_lib/init.lua'`. It also specifies Lua 5.4 is required. ```lua -- fxmanifest.lua for 'your_resource_name' fx_version 'cerulean' game 'gta5' lua54 'yes' -- ox_lib requires Lua 5.4 -- Add ox_lib as a dependency dependencies { 'ox_lib' } -- Load ox_lib's utility functions into your resource's environment shared_script '@ox_lib/init.lua' client_scripts { 'client/main.lua' } server_scripts { 'server/main.lua' } ``` -------------------------------- ### Checking for ox_lib and Using Basic Functions (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/guides/getting-started.md This Lua snippet demonstrates how to check if the `lib` global variable is available (indicating ox_lib loaded correctly) and how to use a basic function like `lib.notify` to display a notification. This code can be placed in either client or server scripts. ```lua -- client/main.lua or server/main.lua if lib then lib.notify({ title = 'ox_lib Loaded!', description = 'Successfully using ox_lib in my resource.', type = 'success' }) else print('Error: ox_lib is not loaded correctly!') end ``` -------------------------------- ### Using ox_lib Progress Bar (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/progress.md This Lua client script example demonstrates the usage of a hypothetical `lib.progressBar` function from ox_lib. It shows how to configure the progress bar with a label, duration, options to disable player controls, and handle the success or cancellation outcome using the function's return value. Includes commented-out examples for animations, props, and a hypothetical `lib.progressCircle`. ```lua -- Client Script Example -- Example using a hypothetical lib.progressBar function local success = lib.progressBar({ label = 'Lockpicking Safe...', duration = 5000, -- Duration in milliseconds useWhileDead = false, canCancel = true, disable = { -- Things to disable while progress bar is active move = true, car = true, combat = true, }, -- Optional animation to play during progress -- anim = { -- dict = 'missheistdockssetup1clipboard@base', -- clip = 'base' -- }, -- Optional prop to attach -- prop = { -- model = `prop_cs_tablet`, -- pos = vector3(0.0, 0.0, 0.0), -- rot = vector3(0.0, 0.0, 0.0) -- } }) if success then print('Lockpicking successful!') lib.notify({ description = 'Safe opened!', type = 'success' }) -- Trigger event for successful lockpick else print('Lockpicking failed or cancelled.') lib.notify({ description = 'Lockpicking cancelled.', type = 'error' }) -- Handle cancellation end -- Example using a hypothetical lib.progressCircle function (might have similar options) -- local successCircle = lib.progressCircle({ -- label = 'Hacking Terminal...', -- duration = 8000, -- position = 'bottom-center', -- Or coordinates -- useWhileDead = false, -- canCancel = true, -- -- ... other options -- }) -- -- if successCircle then -- print('Hacking successful!') -- else -- print('Hacking failed or cancelled.') -- end ``` -------------------------------- ### Using ox_lib Math Utilities (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/utils.md Provides examples of ox_lib math functions, including rounding a number to a specified decimal place and clamping a number within a defined minimum and maximum range. ```Lua -- Round a number to a specific decimal place local rounded = lib.math.round(3.14159, 2) -- rounded will be 3.14 print(rounded) -- Clamp a number within a range local clamped = lib.math.clamp(15, 0, 10) -- clamped will be 10 print(clamped) -- Vector math (examples depend on specific functions available) -- local vec1 = vector3(1.0, 2.0, 3.0) -- local vec2 = vector3(4.0, 5.0, 6.0) -- local distance = lib.math.vdist(vec1, vec2) -- Hypothetical distance function ``` -------------------------------- ### Granting ox_lib ACL Permission (cfg) Source: https://github.com/4timci4/ox_lib-docs/blob/main/guides/configuration.md This example shows how to use the FiveM `add_ace` command in your `server.cfg` or a dedicated permissions file to grant a specific `ox_lib` ACE permission (e.g., for a command) to a group. It also includes a commented-out line showing how to assign a user principal to that group. ```cfg # In your server.cfg or a dedicated permissions.cfg add_ace group.admin oxlib.command.somecommand allow -- Grant permission # add_principal identifier.steam:yoursteamhex group.admin -- Assign user to group ``` -------------------------------- ### Configuring ox_lib Settings (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/guides/configuration.md This hypothetical example demonstrates how configuration options might be structured within the `ox_lib/resource/settings.lua` file. It shows setting boolean flags for debug modes and a default numeric value for notification duration. ```Lua -- ox_lib/resource/settings.lua Config = Config or {} -- Enable debug printing for specific modules (Example, may not exist) Config.Debug = { notifications = false, zones = true } -- Default notification duration Config.DefaultNotifyDuration = 5000 -- milliseconds ``` -------------------------------- ### Configuring VS Code Lua Language Server Library Path Source: https://github.com/4timci4/ox_lib-docs/blob/main/guides/development-environment.md This JSON snippet shows how to configure the Lua Language Server (LLS) in VS Code's settings.json to include the ox_lib resource path in its workspace library. This allows LLS to provide autocompletion, type checking, and diagnostics for ox_lib functions and types. It also demonstrates adding common global variables like 'cfg' and 'lib' to suppress diagnostics for undefined globals. ```json // .vscode/settings.json (Example) { "Lua.workspace.library": [ "c:/fxserver/resources/ox_lib", // Path to your ox_lib // Add paths to other libraries or frameworks if needed ], "Lua.diagnostics.globals": [ "cfg", // Add common globals if needed "lib" ] // Other settings... } ``` -------------------------------- ### Creating a Vehicle Context Menu in ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/context-menu.md This Lua client script example demonstrates how to use a hypothetical `lib.showContext` function to display a context menu when near a vehicle. It defines various options for interacting with the vehicle, including toggling the engine, opening/closing a door, and an admin option to delete the vehicle, showcasing features like icons, `onSelect` callbacks, `disabled` conditions, `restricted` permissions, and `serverEvent` triggers. ```lua -- Client Script Example: Context menu for a vehicle -- Assume we have detected the player is near a vehicle and aiming at it, or using a keybind local vehicle = GetVehiclePedIsIn(PlayerPedId(), false) -- Or get vehicle via raycast/other means if not vehicle then vehicle = lib.getClosestVehicle(GetEntityCoords(PlayerPedId())) end -- Example fallback if vehicle then lib.showContext('vehicle_menu', { title = 'Vehicle Options', options = { { title = 'Toggle Engine', icon = 'fas fa-key', -- serverEvent = 'myResource:toggleVehicleEngine', -- Trigger server event -- args = { netId = VehToNet(vehicle) }, -- Pass vehicle network ID onSelect = function() -- Or handle directly on client local engineRunning = GetIsVehicleEngineRunning(vehicle) SetVehicleEngineOn(vehicle, not engineRunning, false, true) lib.notify({ description = engineRunning and 'Engine stopped.' or 'Engine started.' }) end }, { title = 'Toggle Door', icon = 'fas fa-door-open', disabled = IsVehicleDoorDamaged(vehicle, 0), -- Disable if door is damaged onSelect = function() local doorIndex = 0 -- Front left door if GetVehicleDoorAngleRatio(vehicle, doorIndex) > 0.0 then SetVehicleDoorShut(vehicle, doorIndex, false) else SetVehicleDoorOpen(vehicle, doorIndex, false, false) end end }, { title = 'Admin: Delete Vehicle', icon = 'fas fa-trash', restricted = 'group.admin', -- Only show/allow for admins (requires ACL check) serverEvent = 'myResource:adminDeleteVehicle', args = { netId = VehToNet(vehicle) } }, { title = 'Close Menu', icon = 'fas fa-times' -- No onSelect or event needed, usually closes automatically } } }) end ``` -------------------------------- ### Getting/Setting Vehicle Properties (Hypothetical ox_lib Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/misc-functions.md Shows hypothetical examples of how `ox_lib` might provide functions to get or set vehicle properties like fuel level or dirt level. Note that the exact function names (`lib.getFuel`, `lib.setDirtLevel`) are hypothetical and users should consult the official documentation. ```Lua -- Example: Getting vehicle properties (Check official docs for exact functions) -- local vehicle = GetVehiclePedIsIn(PlayerPedId(), false) -- local fuelLevel = lib.getFuel(vehicle) -- Hypothetical -- lib.setDirtLevel(vehicle, 0.0) -- Hypothetical ``` -------------------------------- ### Example JSON Locale Files Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/locale.md These snippets illustrate the structure and content of typical JSON locale files used by ox_lib. They contain key-value pairs where keys are identifiers used in scripts and values are the translated strings, potentially including placeholders like {item} or {player}. ```JSON // locales/en.json { "welcome_message": "Welcome to the server!", "item_pickup": "You picked up a {item}.", "player_joined": "{player} has joined the server." } ``` ```JSON // locales/es.json { "welcome_message": "¡Bienvenido al servidor!", "item_pickup": "Recogiste un {item}.", "player_joined": "{player} se ha unido al servidor." } ``` -------------------------------- ### Using the locale Function in Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/locale.md This Lua snippet demonstrates how to use the global `locale` function (or `lib.locale`) to retrieve translated strings from the loaded locale files. It shows examples for simple translations and translations involving placeholders, which are replaced dynamically. ```Lua -- Client or Server Script -- Simple translation local welcome = locale('welcome_message') print(welcome) -- Outputs "Welcome to the server!" or "¡Bienvenido al servidor!" depending on loaded locale -- Translation with placeholders local itemName = " téléphone" -- Example item name local pickupMsg = locale('item_pickup', { item = itemName }) lib.notify({ description = pickupMsg }) -- Shows notification with "You picked up a phone." or "Recogiste un teléfono." -- Using placeholders with player names (server-side example) local playerName = GetPlayerName(source) local joinMsg = locale('player_joined', { player = playerName }) TriggerClientEvent('chat:addMessage', -1, { args = { '^2System', joinMsg } }) ``` -------------------------------- ### Playing Animation using Hypothetical ox_lib Wrapper (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/animation.md Illustrates a hypothetical `lib.playAnim` function that could potentially wrap the dictionary request and animation playing logic. It shows calling the function with common parameters and includes an example of stopping the animation after a delay using `ClearPedTasks`. Note that the exact function name and parameters should be verified in the official `ox_lib` documentation. ```lua -- Hypothetical lib.playAnim example (check official docs for actual implementation) local playerPed = PlayerPedId() local animDict = 'amb@world_human_leaning@male@wall@back@hands_crossed@base' local animName = 'base' local duration = -1 -- Loop indefinitely local flag = 49 -- Common flag for looping, upper body only, controllable -- Assuming lib.playAnim handles requesting the dict internally local success = lib.playAnim(playerPed, animDict, animName, duration, flag) if success then print('Playing animation...') else print('Failed to play animation.') end -- To stop the animation, you might use ClearPedTasks(playerPed) or a specific stop function if provided. -- Example: Stop after 5 seconds SetTimeout(5000, function() print('Stopping animation...') ClearPedTasks(playerPed) end) ``` -------------------------------- ### Finding Closest Vehicle using ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/closest-entity.md This snippet demonstrates how to use `lib.getClosestVehicle` to find the nearest vehicle to the current player's location. It shows how to get the vehicle's model name and the distance. ```lua -- Client Script local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) -- Find the closest player (excluding self) within 10 units local closestPlayer, closestDistance = lib.getClosestPlayer(coords, { PlayerPedId() }) -- Exclude self if closestPlayer then local serverId = GetPlayerServerId(closestPlayer) print(('Closest player found: %s (Server ID: %s) at distance: %.2f'):format(GetPlayerName(closestPlayer), serverId, closestDistance)) else print('No other players nearby.') end -- Example (Finding the closest vehicle): local closestVehicle, closestDistance = lib.getClosestVehicle(coords) if closestVehicle then local model = GetEntityModel(closestVehicle) local modelName = GetDisplayNameFromVehicleModel(model) -- Requires game data print(('Closest vehicle found: %s (Model: %s) at distance: %.2f'):format(closestVehicle, modelName, closestDistance)) else print('No vehicles nearby.') end ``` -------------------------------- ### Scheduling and Clearing Timers with ox_lib Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/timers-intervals.md Demonstrates how to use `SetTimeout` to execute a function once after a specified delay (in milliseconds) and `ClearTimeout` to cancel a pending timeout using the ID returned by `SetTimeout`. Includes examples of a simple delayed action and cancelling a timeout before it runs. ```lua -- Execute a function after 2 seconds local function delayedAction() print('This message appears after 2 seconds.') end local timeoutId = SetTimeout(2000, delayedAction) -- Delay in milliseconds print('Timeout scheduled with ID:', timeoutId) -- Example of cancelling a timeout before it executes local function anotherAction() print('This should ideally not appear if cleared in time.') end local anotherTimeoutId = SetTimeout(5000, anotherAction) -- Cancel the timeout after 1 second SetTimeout(1000, function() print('Clearing timeout with ID:', anotherTimeoutId) ClearTimeout(anotherTimeoutId) end) ``` -------------------------------- ### Finding Closest Player using ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/closest-entity.md This snippet demonstrates how to use `lib.getClosestPlayer` to find the nearest player to the current player's location, excluding the current player. It shows how to get the player's server ID, name, and the distance. ```lua -- Client Script local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) -- Find the closest player (excluding self) within 10 units local closestPlayer, closestDistance = lib.getClosestPlayer(coords, { PlayerPedId() }) -- Exclude self if closestPlayer then local serverId = GetPlayerServerId(closestPlayer) print(('Closest player found: %s (Server ID: %s) at distance: %.2f'):format(GetPlayerName(closestPlayer), serverId, closestDistance)) else print('No other players nearby.') end -- Example (Finding the closest vehicle): local closestVehicle, closestDistance = lib.getClosestVehicle(coords) if closestVehicle then local model = GetEntityModel(closestVehicle) local modelName = GetDisplayNameFromVehicleModel(model) -- Requires game data print(('Closest vehicle found: %s (Model: %s) at distance: %.2f'):format(closestVehicle, modelName, closestDistance)) else print('No vehicles nearby.') end ``` -------------------------------- ### Managing Recurring Intervals with ox_lib Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/timers-intervals.md Illustrates the use of `SetInterval` to repeatedly execute a function at a fixed interval (in milliseconds) and `ClearInterval` to stop the recurring execution using the interval ID. Also shows an advanced example of dynamically changing the interval duration using `ox_lib`'s specific implementation. ```lua -- Execute a function every 1 second local counter = 0 local function recurringAction() counter = counter + 1 print('Interval tick:', counter) if counter >= 5 then print('Clearing interval...') ClearInterval(intervalId) -- Stop the interval after 5 ticks end end local intervalId = SetInterval(1000, recurringAction) -- Interval in milliseconds print('Interval scheduled with ID:', intervalId) -- Example: Changing interval duration (using the custom SetInterval from init.lua) local dynamicIntervalId local currentDelay = 2000 dynamicIntervalId = SetInterval(currentDelay, function() print(('Running with delay: %dms'):format(currentDelay)) currentDelay = currentDelay - 500 -- Decrease delay over time if currentDelay < 500 then print('Clearing dynamic interval.') ClearInterval(dynamicIntervalId) else SetInterval(dynamicIntervalId, currentDelay) -- Update the interval delay end end) ``` -------------------------------- ### Creating Simple Input Dialog (ox_lib, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/input.md Demonstrates how to create a basic input dialog using `lib.inputDialog` to prompt the user for a single text input (name). It shows how to handle the returned value (which is a table) and display a notification based on the input or cancellation. ```Lua -- Client Script Example -- Simple input dialog local inputText = lib.inputDialog('Enter Your Name', { 'Your name:' }) if inputText then print('User entered:', json.encode(inputText)) -- inputText is usually a table, e.g., { "Your name:" = "John Doe" } local name = inputText[1] -- Access by index if labels are simple if name and name ~= '' then lib.notify({ description = 'Hello, ' .. name }) -- Trigger server event with the name, etc. else lib.notify({ description = 'Input cancelled or empty.', type = 'warning' }) end else lib.notify({ description = 'Dialog failed to open or was cancelled.', type = 'error' }) end ``` -------------------------------- ### Creating and Handling BoxZone Events (ox_lib, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/zones-points.md This snippet demonstrates how to define parameters for a BoxZone, create it using `lib.zones.box`, and attach event handlers (`onPlayerInside`, `onPlayerOutside`) to react when the local player enters or exits the zone. It shows how to use `lib.notify` for feedback and includes options like `name`, `heading`, `minZ`, `maxZ`, and `debugPoly`. ```lua -- Example: Creating a BoxZone and reacting to entry/exit -- Define the zone parameters local center = vector3(100.0, 200.0, 70.0) local length = 10.0 local width = 5.0 local options = { name = 'myStoreEntrance', heading = 90.0, minZ = 68.0, maxZ = 72.0, debugPoly = true -- Show the zone visually for debugging } -- Create the zone local storeZone = lib.zones.box(center, length, width, options) -- Event triggered when a player enters the zone storeZone:onPlayerInside(function(player) if player == PlayerId() then -- Check if it's the local player lib.notify({ description = 'You entered the store zone.' }) -- Trigger interaction prompt, etc. end end) -- Event triggered when a player exits the zone storeZone:onPlayerOutside(function(player) if player == PlayerId() then lib.notify({ description = 'You left the store zone.' }) -- Hide interaction prompt, etc. end end) ``` -------------------------------- ### Creating and Handling Point Interactions (ox_lib, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/zones-points.md This snippet illustrates how to create an interaction point using `lib.points.new`. It defines the center coordinate and radius, includes options like `name`, `radius`, `useZ`, and `debugPoint`, and demonstrates using the `onNearby` event to show/hide UI text (`lib.showTextUI`, `lib.hideTextUI`) and detect player input (`IsControlJustPressed`) for interaction. ```lua -- Example: Creating an interaction point local pointCenter = vector3(105.0, 202.0, 70.0) local pointOptions = { name = 'shopCounter', radius = 1.5, useZ = true, -- Consider Z axis for distance check debugPoint = true } local shopPoint = lib.points.new(pointCenter, pointOptions.radius, pointOptions) shopPoint:onNearby(function() -- Show interaction text like "[E] Talk to Shopkeeper" lib.showTextUI('[E] Talk to Shopkeeper') if IsControlJustPressed(0, 38) then -- 38 is E key by default print('Interacting with shopkeeper...') -- Trigger shop logic end end, function() -- Hide interaction text when player moves away lib.hideTextUI() end) ``` -------------------------------- ### Playing Animation using Standard FiveM Native after ox_lib Request (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/animation.md Shows the standard method of playing an animation using the FiveM native `TaskPlayAnim` after successfully requesting the animation dictionary with `lib.requestAnimDict`. This approach is used when `ox_lib` does not provide a higher-level wrapper for playing animations directly. ```lua -- Standard approach after requesting dict local playerPed = PlayerPedId() local animDict = 'amb@world_human_leaning@male@wall@back@hands_crossed@base' local animName = 'base' if lib.requestAnimDict(animDict) then TaskPlayAnim(playerPed, animDict, animName, 8.0, -8.0, -1, 49, 0, false, false, false) else print('Dict not loaded, cannot play anim.') end ``` -------------------------------- ### Registering a Command with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/misc-functions.md Demonstrates how to register a new command using `lib.addCommand`. It includes defining command help text, parameters with types and help, and restricting access based on ACE permissions. The function callback receives source, arguments, and raw command string. ```Lua -- Example: Registering a command with ox_lib lib.addCommand('mycommand', { help = 'This is a test command', params = { -- Define expected parameters { name = 'target', type = 'playerId', help = 'Target Player ID' }, { name = 'amount', type = 'number', help = 'Amount', optional = true } }, restricted = 'group.admin' -- Requires 'group.admin' ace }, function(source, args, rawCommand) local targetId = args.target local amount = args.amount or 100 -- Default amount if not provided print(('Player %s used /mycommand on player %s with amount %d'):format(source, targetId, amount)) -- Command logic here... end) ``` -------------------------------- ### Displaying Basic Notifications (Client, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/notifications.md Demonstrates how to use the `lib.notify` function on the client-side to show notifications. It covers basic usage with title, description, and type, as well as advanced options like specifying an ID, icon, icon color, and duration. ```lua -- Basic notification lib.notify({ title = 'Success', description = 'Player data saved successfully.', type = 'success' -- 'success', 'inform', 'error', 'warning' }) -- Notification with an icon lib.notify({ id = 'player_saved', -- Optional ID to prevent duplicates or allow updates title = 'Player Saved', description = 'Your progress has been saved.', icon = 'fas fa-save', -- Font Awesome icon iconColor = '#00ff00', duration = 5000 -- Duration in milliseconds }) ``` -------------------------------- ### Registering FiveM Events (Server, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/events.md This Lua snippet demonstrates how to register network and local events on the FiveM server. It shows RegisterNetEvent to handle client requests, identifying the source player, and AddEventHandler for built-in server events like playerConnecting. It also includes triggering a response event back to the client using TriggerClientEvent. ```Lua -- Register an event that clients can trigger RegisterNetEvent('myResource:requestData', function(requestedInfo) local sourcePlayer = source -- The server ID of the client who triggered the event print(('Player %s requested data: %s'):format(GetPlayerName(sourcePlayer), requestedInfo)) -- Process the request and send data back (e.g., using a callback or another event) local responseData = { info = requestedInfo, processed = true } TriggerClientEvent('myResource:receiveData', sourcePlayer, responseData) end) -- Register a handler for a built-in server event AddEventHandler('playerConnecting', function(playerName, setKickReason, deferrals) print(('Player %s is connecting...'):format(playerName)) -- You can add checks or deferrals here end) ``` -------------------------------- ### Using ox_lib Callbacks for Client-Server Communication (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/callbacks.md This snippet demonstrates the basic flow of an ox_lib callback. The client initiates a request using `lib.callback`, providing a unique identifier and arguments. The server registers a handler for that identifier using `lib.callback.register`, processes the request, and returns data which is then received by the client. ```Lua -- Client Script local result = lib.callback('myResource:getServerData', false, 'someArgument') print(json.encode(result)) -- Server Script lib.callback.register('myResource:getServerData', function(source, argument) print(('Callback received from %s with argument: %s'):format(source, argument)) -- Process data or perform actions local data = { message = 'Hello from server!', received = argument } return data -- This data is sent back to the client end) ``` -------------------------------- ### Using ox_lib String Utilities (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/utils.md Illustrates basic string manipulation using ox_lib functions, such as trimming whitespace, splitting a string by a delimiter into a table, and generating a random string. ```Lua local myString = " Hello World! " -- Trim whitespace local trimmed = lib.string.trim(myString) -- trimmed will be "Hello World!" print(trimmed) -- Split string into a table local parts = lib.string.split("apple,banana,cherry", ",") -- parts will be { "apple", "banana", "cherry" } print(json.encode(parts)) -- Generate a random string local randomId = lib.string.random(8) -- e.g., "a3fG7hJk" print(randomId) ``` -------------------------------- ### Requesting and Using Assets with ox_lib Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/streaming-requests.md This Lua client script demonstrates how to use `ox_lib` functions to request game assets before using them. The first part shows requesting a vehicle model (`adder`) and then spawning the vehicle, followed by marking the model as no longer needed. The second part shows requesting an animation dictionary (`missheistdockssetup1clipboard@base`) and then playing an animation from it. It highlights the asynchronous nature of asset loading and the importance of waiting for assets to load. ```Lua -- Client Script -- Example: Spawning a vehicle after requesting its model local vehicleModel = `adder` -- Using backticks for hash lookup -- Request the model if lib.requestModel(vehicleModel) then -- Model is loaded, now spawn the vehicle local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) local heading = GetEntityHeading(playerPed) local vehicle = CreateVehicle(vehicleModel, coords.x, coords.y, coords.z, heading, true, true) -- Mark the model as no longer needed (important for memory management) SetModelAsNoLongerNeeded(vehicleModel) print(('Spawned vehicle %s'):format(vehicleModel)) else print(('Failed to load vehicle model: %s'):format(vehicleModel)) end -- Example: Playing an animation after requesting its dictionary local animDict = 'missheistdockssetup1clipboard@base' local animName = 'base' -- Request the animation dictionary if lib.requestAnimDict(animDict) then -- Dictionary is loaded, play the animation local playerPed = PlayerPedId() TaskPlayAnim(playerPed, animDict, animName, 8.0, -8.0, -1, 1, 0, false, false, false) -- Dictionary can often be removed after starting the task, but check specific needs -- RemoveAnimDict(animDict) -- Be careful with timing if animation needs the dict longer print(('Playing animation from %s'):format(animDict)) else print(('Failed to load animation dictionary: %s'):format(animDict)) end ``` -------------------------------- ### Using the cache Table - Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/core-modules.md Illustrates how to store and retrieve simple data using the global `cache` table and how to use `cache` with a function to cache the result of an expensive operation, preventing redundant computation. ```Lua -- Storing data cache('mySharedValue', 123) -- Retrieving data in the same or another resource local value = cache.mySharedValue if value then print('Retrieved value:', value) -- Output: Retrieved value: 123 end -- Using cache with a function (caches the result) local expensiveData = cache('expensiveDataKey', function() -- Simulate fetching data Wait(1000) return { data = 'fetched after 1s' } end) print(json.encode(expensiveData)) -- First time waits, subsequent times return cached value instantly ``` -------------------------------- ### Using ox_lib Table Utilities (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/utils.md Demonstrates common table manipulation functions from ox_lib, including checking for element existence, finding an element's index, and merging tables with overrides. ```Lua local myTable = { 'apple', 'banana', 'cherry' } -- Check if an element exists if lib.table.contains(myTable, 'banana') then print('Found banana!') end -- Find the index of an element local index = lib.table.findIndex(myTable, 'cherry') -- index will be 3 local defaults = { setting1 = true, setting2 = 10 } local overrides = { setting2 = 25, setting3 = false } -- Merge tables (overrides takes precedence) local merged = lib.table.merge(defaults, overrides) -- merged will be { setting1 = true, setting2 = 25, setting3 = false } print(json.encode(merged)) ``` -------------------------------- ### Triggering and Handling FiveM Events (Client, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/events.md This Lua snippet illustrates how to trigger a network event from the client to the server using TriggerServerEvent. It also shows how to register a handler for a server response event using RegisterNetEvent and a handler for a built-in client event using AddEventHandler. It uses json.encode and lib.notify from ox_lib. ```Lua -- Trigger the server event TriggerServerEvent('myResource:requestData', 'player_stats') print('Requested player stats from server...') -- Register a handler for the server's response event RegisterNetEvent('myResource:receiveData', function(data) print('Received data from server:', json.encode(data)) lib.notify({ title = 'Data Received', description = 'Server sent: ' .. data.info }) end) -- Register a handler for a built-in client event AddEventHandler('onClientMapStart', function() print('Client map has started.') -- Perform actions needed when the player spawns into the world end) ``` -------------------------------- ### Registering a Keybind with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/misc-functions.md Illustrates how to register a new keybind using `lib.addKeybind`. It requires a unique name, a description, a default key assignment, and an `onPressed` callback function that executes when the key is pressed. Optional ACE restrictions can also be applied. ```Lua -- Example: Registering a keybind lib.addKeybind({ name = 'toggle_hud', description = 'Toggle HUD Visibility', defaultKey = 'F10', onPressed = function() -- Logic to toggle HUD print('HUD toggled!') end, -- restricted = 'group.user' -- Optional ace requirement }) ``` -------------------------------- ### Creating Multi-Field Input Dialog with Validation (ox_lib, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/input.md Illustrates creating a more complex input dialog with multiple fields of different types (number, text), including validation (required, min/max) and icons. It shows how to access values from the returned table and perform basic checks before proceeding. ```Lua -- Input dialog with multiple fields and validation local inputs = lib.inputDialog('Transfer Money', { { type = 'number', label = 'Target Player ID', required = true, icon = 'user' }, { type = 'number', label = 'Amount', placeholder = 'Enter amount', required = true, min = 1, max = 10000, icon = 'dollar-sign' }, { type = 'text', label = 'Reason', placeholder = 'Optional reason', icon = 'comment' } }) if inputs then print('Transfer details:', json.encode(inputs)) local targetId = tonumber(inputs[1]) local amount = tonumber(inputs[2]) local reason = inputs[3] if targetId and amount then print(('Attempting to transfer %d to player %d for reason: %s'):format(amount, targetId, reason or 'N/A')) -- Trigger server event for transfer logic else lib.notify({ description = 'Invalid input provided.', type = 'error' }) end else lib.notify({ description = 'Transfer cancelled.', type = 'inform' }) end ``` -------------------------------- ### Using the lib Table - Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/core-modules.md Demonstrates how to check if the ox_lib library is loaded and how to call a function from the global `lib` table, such as `lib.getNearbyVehicles`, to interact with game elements. ```Lua -- Check if ox_lib is loaded if lib then -- Use a function local vehicles = lib.getNearbyVehicles(GetEntityCoords(PlayerPedId()), 10.0) print(#vehicles .. ' vehicles nearby') else print('ox_lib not loaded!') end ``` -------------------------------- ### Displaying Proximity Text UI in ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/ui-helpers.md Demonstrates how to use `lib.showTextUI` and `lib.hideTextUI` to display an interaction prompt when a player is within a certain distance of a specific point in the game world. It uses a game loop to periodically check distance and player input. ```lua -- Client Script Example: Show interaction prompt near a point local interactionPoint = vector3(120.0, -300.0, 45.0) local playerPed = PlayerPedId() local distanceThreshold = 2.0 local showingText = false CreateThread(function() while true do Wait(250) -- Check periodically local playerCoords = GetEntityCoords(playerPed) local distance = #(playerCoords - interactionPoint) -- Calculate distance if distance < distanceThreshold then if not showingText then lib.showTextUI('[E] Interact') -- Show the prompt showingText = true end -- Check if the player presses the interaction key if IsControlJustPressed(0, 38) then -- E key print('Interaction triggered!') -- Perform interaction logic lib.hideTextUI() -- Hide text after interaction (optional) showingText = false Wait(1000) -- Add a small delay to prevent immediate re-trigger end else if showingText then lib.hideTextUI() -- Hide the prompt when player moves away showingText = false end end end end) ``` -------------------------------- ### Configuring fxmanifest.lua for Locales Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/locale.md This snippet shows how to modify your fxmanifest.lua file to ensure locale JSON files are included in your resource and how to load the ox_lib initialization script, which handles automatic locale loading. ```Lua -- fxmanifest.lua -- Ensure locale files are included files { 'locales/en.json', 'locales/es.json', -- Add other languages } -- Load the locale module (often done automatically by init.lua) -- shared_script '@ox_lib/init.lua' -- if not already present ``` -------------------------------- ### Requesting Animation Dictionary with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/animation.md Demonstrates how to use `lib.requestAnimDict` to asynchronously load an animation dictionary. It checks the return value to ensure the dictionary is loaded successfully before attempting to use animations from it, preventing errors. ```lua local animDict = 'amb@world_human_leaning@male@wall@back@hands_crossed@base' if lib.requestAnimDict(animDict) then -- Dictionary is loaded, safe to use animations from it print(('Animation dictionary %s loaded.'):format(animDict)) else print(('Failed to load animation dictionary: %s'):format(animDict)) return -- Don't proceed if dict failed to load end ``` -------------------------------- ### Perform Raycast from Player Camera (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/functions/raycasting.md This Lua function demonstrates how to perform a raycast from the player's camera position and direction using a hypothetical ox_lib raycast function. It calculates the camera's position and direction, casts a ray up to a specified distance, ignores the player ped, and checks if the ray hits an entity (ped, vehicle, or object) or the map, printing the result. Requires FiveM natives for camera and entity checks, and json.encode for coordinates. ```lua -- Client Script Example: Raycast from player's camera local function getEntityPlayerIsLookingAt(distance) local camCoords = GetGameplayCamCoord() local camRot = GetGameplayCamRot(2) -- Use order 2 for XYZ rotation local direction = RotToDir(camRot) -- Convert rotation to a direction vector -- Perform the raycast -- The exact function and parameters might differ (e.g., lib.raycast.new, lib.raycast.cam) -- Assuming a hypothetical lib.raycast function: local hit, coords, entity = lib.raycast(camCoords, direction, distance, { PlayerPedId() }, 7) -- Parameters: origin, direction, maxDistance, entitiesToIgnore, intersectionFlags if hit and entity ~= 0 then print(('Raycast hit entity: %d at coords: %s'):format(entity, json.encode(coords))) if IsEntityAPed(entity) then print("It's a ped!") elseif IsEntityAVehicle(entity) then print("It's a vehicle!") elseif IsEntityAnObject(entity) then print("It's an object!") end return entity, coords elseif hit then print(('Raycast hit map at coords: %s'):format(json.encode(coords))) return nil, coords -- Hit the map, not an entity else print('Raycast did not hit anything.') return nil, nil -- Missed end end -- In a loop or on key press: -- local targetEntity, targetCoords = getEntityPlayerIsLookingAt(50.0) -- Check up to 50 units away ``` -------------------------------- ### Triggering Notifications for Client (Server, Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/ui/notifications.md Shows how to trigger a notification on a specific client from a server script using the `TriggerClientEvent` function and the `ox_lib:notify` event. This is the recommended server-side method as `lib.notify` is deprecated on the server. ```lua -- Assuming 'source' is the player's server ID TriggerClientEvent('ox_lib:notify', source, { title = 'Admin Action', description = 'You have been kicked by an administrator.', type = 'error' }) -- Note: For server-side locale support, ensure locales are configured correctly. -- The lib.notify function itself is deprecated on the server, use the event. ``` -------------------------------- ### Storing and Retrieving Cache Values in ox_lib Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/cache.md Demonstrates basic usage of the ox_lib cache, including storing values directly via the table syntax, using the cache() function for storage, retrieving values, caching the result of a function call using cache(), and setting a timeout for a cached value. Requires `json.encode` for printing complex types and `Wait` for simulating operations. ```lua -- Storing a simple value cache.myValue = 100 -- or cache('myOtherValue', { x = 1, y = 2 }) -- Retrieving a value local val1 = cache.myValue local val2 = cache.myOtherValue if val1 then print('myValue:', val1) -- Output: myValue: 100 end if val2 then print('myOtherValue:', json.encode(val2)) -- Output: myOtherValue: {"x":1,"y":2} end -- Using cache() function to cache function results -- The function only runs the first time cache() is called with this key. local function getPlayerData(playerId) print('Fetching player data for', playerId) -- Simulate database query or expensive operation Wait(500) return { name = GetPlayerName(playerId), health = GetEntityHealth(GetPlayerPed(playerId)) } end local playerId = PlayerId() local playerData = cache('playerData_' .. playerId, function() return getPlayerData(playerId) end) print('Player Data (cached):', json.encode(playerData)) -- Subsequent calls with the same key return the cached value instantly local playerDataAgain = cache('playerData_' .. playerId, function() print("This won't run") end) print('Player Data (again):', json.encode(playerDataAgain)) -- Caching with a timeout (value becomes nil after timeout) cache('temporaryData', 'This will expire', 10000) -- Expires after 10 seconds ``` -------------------------------- ### Checking Player ACL Permission (Lua) Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/acl.md This server-side Lua snippet demonstrates how to check if a player has a specific ACL permission ('myResource.adminCommand') using a hypothetical lib.acl.check function. It defines a helper function 'canPlayerUseAdminCommand' and registers a command 'admincmd' that utilizes this check before executing its logic. It also shows the necessary server.cfg entries to define and assign the ace. ```Lua -- Server-side example local function canPlayerUseAdminCommand(playerId) -- Check if the player has the 'myResource.adminCommand' ace -- The exact function might vary, check official docs (e.g., lib.acl.isAllowed, lib.acl.check) -- Assuming a hypothetical lib.acl.check function: if lib.acl.check(playerId, 'myResource.adminCommand') then return true else lib.notify(playerId, { description = 'You do not have permission to use this command.', type = 'error' }) return false end end RegisterCommand('admincmd', function(source, args, rawCommand) local playerId = source if canPlayerUseAdminCommand(playerId) then -- Execute admin command logic print(('Player %s used admin command'):format(GetPlayerName(playerId))) end }, false) -- false = command requires permission check -- In your server.cfg or permissions.cfg: -- add_ace group.admin myResource.adminCommand allow -- add_principal identifier.steam:yoursteamhex group.admin ``` -------------------------------- ### Watching for Cache Key Changes with lib.onCache in ox_lib Lua Source: https://github.com/4timci4/ox_lib-docs/blob/main/modules/cache.md Illustrates how to use `lib.onCache` to register a callback function that executes whenever a specific cache key's value is updated. The callback receives the new and old values. Subsequently updating the watched key (`cache.sharedSetting`) triggers the registered callback. Requires `json.encode` for formatting output. ```lua lib.onCache('sharedSetting', function(newValue, oldValue) print(('sharedSetting changed from %s to %s'):format(json.encode(oldValue), json.encode(newValue))) -- Update UI or logic based on the new setting end) -- Later, in the same or another resource: cache.sharedSetting = { theme = 'dark' } -- This will trigger the lib.onCache callback ```