### Using ox_lib Math Utilities (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/utils.md Shows examples of `lib.math` functions for common mathematical tasks, including rounding a number to a specified decimal precision (`round`) and clamping a number within a minimum and maximum range (`clamp`). Includes commented-out examples for potential vector math functions. ```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 ``` -------------------------------- ### Example ox_lib Locale JSON Files (JSON) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/locale.md These examples demonstrate the standard structure for ox_lib locale files using JSON. They show how to define translation keys and include placeholders (e.g., {item}, {player}) that can be replaced dynamically when retrieving the string. ```JSON // locales/en.json { "welcome_message": "Welcome to the server!", "item_pickup": "You picked up a {item}.", "player_joined": "{player} has joined the server." } // locales/es.json { "welcome_message": "¡Bienvenido al servidor!", "item_pickup": "Recogiste un {item}.", "player_joined": "{player} se ha unido al servidor." } ``` -------------------------------- ### Checking ox_lib Load Status and Using lib Table (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/core-modules.md Demonstrates how to check if the global 'lib' table, provided by ox_lib, is available and ready for use. It shows a basic example of accessing a function like '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 ``` -------------------------------- ### Configuring ox_lib Settings in Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/guides/configuration.md Demonstrates how to define configuration options within the ox_lib/resource/settings.lua file. This example shows setting debug flags for specific modules and a default 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 ``` -------------------------------- ### Getting/Setting Vehicle Properties with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/misc-functions.md Provides hypothetical examples of how `ox_lib` might be used to interact with vehicle properties, such as getting the fuel level or setting the dirt level. It includes getting the player's current vehicle. Note that the specific functions (`lib.getFuel`, `lib.setDirtLevel`) are marked as hypothetical. ```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 ``` -------------------------------- ### Playing Animation with Hypothetical ox_lib Helper (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/animation.md This example illustrates a hypothetical `lib.playAnim` function that might wrap the dictionary request and animation playing logic. It shows how to call it with parameters like ped, dictionary name, animation name, duration, and flags. It also includes a `SetTimeout` to demonstrate how to stop the animation after a delay using `ClearPedTasks`. ```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) ``` -------------------------------- ### Scheduling and Cancelling Timers with ox_lib Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/timers-intervals.md Demonstrates how to use `SetTimeout` to execute a function once after a specified delay and `ClearTimeout` to cancel a pending timeout using `ox_lib`. Includes examples of scheduling a single action and scheduling a cancellation action. ```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) ``` -------------------------------- ### Requesting and Using FiveM Assets with ox_lib Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/streaming-requests.md This snippet demonstrates how to use ox_lib functions like `lib.requestModel` and `lib.requestAnimDict` to asynchronously load game assets (a vehicle model and an animation dictionary) before using them. It includes examples of spawning a vehicle and playing an animation after successful loading, and shows how to mark models as no longer needed for memory management. ```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 ``` -------------------------------- ### Managing Recurring Intervals with ox_lib Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/timers-intervals.md Shows how to use `SetInterval` to repeatedly execute a function at a fixed interval and `ClearInterval` to stop it. Also includes an example demonstrating `ox_lib`'s specific implementation allowing dynamic interval duration changes. ```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) ``` -------------------------------- ### Using lib.progressBar in Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/ui/progress.md This client-side Lua example demonstrates how to call a hypothetical `lib.progressBar` function. It configures the progress bar with a label, duration, options to disable player controls during the action, and handles the success or cancellation outcome using conditional logic and notifications. ```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 Locale Function (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/locale.md This snippet illustrates how to use the global 'locale' function (or 'lib.locale') in Lua scripts to retrieve translated strings. It shows examples for simple translations and for translations that require replacing placeholders with dynamic values, suitable for notifications or chat messages. ```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 } }) ``` -------------------------------- ### Using ox_lib Table Utilities (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/utils.md Demonstrates common operations using `lib.table` functions, including checking for element existence (`contains`), finding an element's index (`findIndex`), and merging tables (`merge`). Shows how to initialize tables and print results. ```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)) ``` -------------------------------- ### Creating and Reacting to BoxZone Entry/Exit (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/zones-points.md This snippet demonstrates how to create a BoxZone using `lib.zones.box` with specified center, dimensions, and options. It then shows how to attach event handlers using `:onPlayerInside` and `:onPlayerOutside` to react when the local player enters or exits the zone, using `lib.notify` for feedback. ```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) ``` -------------------------------- ### Configuring VS Code Settings for Lua Language Server Source: https://github.com/4timci4/ox_lib-docss/blob/main/guides/development-environment.md This JSON snippet shows how to configure Visual Studio Code's settings.json file to make the Lua Language Server aware of the ox_lib resource and common FiveM globals. It involves adding the path to your ox_lib folder to the 'Lua.workspace.library' array and optionally adding common globals like 'cfg' and 'lib' to 'Lua.diagnostics.globals'. This enables features like autocompletion and type checking for ox_lib functions and FiveM natives. ```JSON { "Lua.workspace.library": [ "c:/fxserver/resources/ox_lib", "/path/to/other/library" ], "Lua.diagnostics.globals": [ "cfg", "lib" ] } ``` -------------------------------- ### Playing Animation with FiveM Native after Requesting Dict (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/animation.md This snippet shows the standard FiveM approach to playing an animation using the `TaskPlayAnim` native. It assumes the animation dictionary has already been successfully loaded (e.g., using `lib.requestAnimDict`). It demonstrates the parameters required for `TaskPlayAnim`. ```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 ``` -------------------------------- ### Using ox_lib String Utilities (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/utils.md Illustrates basic string manipulation with `lib.string`, including removing leading/trailing whitespace (`trim`), splitting a string into a table based on a delimiter (`split`), and generating a random string of a specified length (`random`). Prints the results of each operation. ```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) ``` -------------------------------- ### Creating Input Dialogs with ox_lib in Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/ui/input.md This Lua client script demonstrates how to use lib.inputDialog for both simple single-field text input and complex multi-field inputs with validation, placeholders, and icons. It shows how to handle the dialog's return value, which is typically a table containing the user's input, and how to process or validate the entered data. ```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 -- 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 ``` -------------------------------- ### Registering Command with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/misc-functions.md Demonstrates how to register a new command using `lib.addCommand`. It shows defining command help text, parameters with types and help, restricting access with ACE permissions, and providing the callback function executed when the command is used. ```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) ``` -------------------------------- ### Performing Camera Raycast with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/raycasting.md Demonstrates a client-side function to perform a raycast from the player's camera using a hypothetical ox_lib function. It calculates the camera's position and direction, executes the raycast, and checks if an entity or the map was hit, printing details to the console. Requires ox_lib and runs within the FiveM client environment. ```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 ``` -------------------------------- ### Creating and Reacting to Interaction Point (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/zones-points.md This snippet illustrates how to create a point using `lib.points.new` for defining interaction locations. It uses the `:onNearby` event with two callback functions: one triggered when the player is near (showing UI via `lib.showTextUI` and checking for key presses with `IsControlJustPressed`) and another when the player moves away (hiding UI via `lib.hideTextUI`). ```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) ``` -------------------------------- ### Storing and Retrieving Data with cache Table (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/core-modules.md Illustrates the usage of the global 'cache' table for storing and retrieving data. It shows how to store simple values and how to use 'cache' with a function to cache the results of potentially expensive operations for faster subsequent access. ```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 ``` -------------------------------- ### Displaying Basic Notifications (Client-side, Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/ui/notifications.md Demonstrates how to use the `lib.notify` function on the client-side to display various types of notifications with options for title, description, type, duration, and icons. Requires the ox_lib client resource. ```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 }) ``` -------------------------------- ### Using ox_lib Callbacks for Client-Server Communication (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/callbacks.md This snippet demonstrates the basic usage of ox_lib callbacks. The client script initiates a callback request to the server with an argument, and the server script registers a handler for that callback, processes the request, and returns data back to 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) ``` -------------------------------- ### Registering Keybind with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/misc-functions.md Illustrates registering a keybind using `lib.addKeybind`. It includes setting a unique name, description, default key, and the `onPressed` callback function that runs when the key is pressed. An optional `restricted` field is commented out. ```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 }) ``` -------------------------------- ### Basic Cache Operations (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/cache.md Demonstrates fundamental usage of the ox_lib cache, including storing and retrieving values using both table syntax and the cache() function. It also shows how to cache the result of a function call (executing only on the first access) and how to set a timeout for a cached value. ```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(player 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 ``` -------------------------------- ### Show and Hide Text UI Prompt with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/ui/ui-helpers.md Demonstrates how to use `lib.showTextUI` and `lib.hideTextUI` in a client script to display an interaction prompt when a player is near a specific point. It checks the player's distance periodically and shows/hides the text accordingly, also including basic input handling for interaction. ```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) ``` -------------------------------- ### Displaying Vehicle Context Menu with ox_lib (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/ui/context-menu.md This client-side Lua snippet demonstrates how to use `ox_lib`'s context menu feature to display options when a player is near a vehicle. It checks for a vehicle, then calls `lib.showContext` with a list of options including toggling the engine, toggling a door, and an admin option to delete the vehicle. Options can trigger client-side functions (`onSelect`) or server events (`serverEvent`) and can have conditions (`disabled`, `restricted`). Requires `ox_lib` and FiveM/RedM environment. ```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 ``` -------------------------------- ### Triggering Server Events and Handling Client Events in Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/events.md This Lua snippet illustrates how a client script can trigger a network event on the server ('myResource:requestData'), register a handler ('RegisterNetEvent') to receive a response from the server ('myResource:receiveData'), and handle a built-in client event ('AddEventHandler') like 'onClientMapStart'. It also shows using ox_lib for notifications. ```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 Network and Built-in Server Events in Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/events.md This Lua snippet demonstrates how to register a network event ('myResource:requestData') on the server that clients can trigger, and how to handle a built-in server event ('playerConnecting') using AddEventHandler. It shows accessing the source player and triggering a client event in response to a network event. ```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) ``` -------------------------------- ### Granting ox_lib ACL Permission in server.cfg Source: https://github.com/4timci4/ox_lib-docss/blob/main/guides/configuration.md Illustrates how to use the FiveM ACL system (ace permissions) in your server.cfg or permissions.cfg to grant a group permission to use a specific ox_lib feature, such as a hypothetical command. ```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 fxmanifest for ox_lib Locales (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/locale.md This snippet shows how to declare locale files within your fxmanifest.lua to ensure they are included in your resource. It also mentions the shared_script line often used to initialize ox_lib. ```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-docss/blob/main/functions/animation.md This snippet demonstrates how to use `lib.requestAnimDict` to asynchronously load an animation dictionary. It checks the boolean return value to confirm if the dictionary was successfully loaded before attempting to use animations from it. If loading fails, it prints an error and stops execution. ```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 ``` -------------------------------- ### Checking Player ACL Permissions in ox_lib Lua Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/acl.md This server-side Lua snippet demonstrates how to check if a player has a specific ACL permission (ace) using a hypothetical `lib.acl.check` function and how to integrate this check into a FiveM command registration. It includes comments showing how to define the required ace in the server configuration. ```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 Cache Key Changes (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/modules/cache.md Illustrates how to use the lib.onCache function to register a callback that executes whenever the value associated with a specific cache key is updated. The callback receives both the new and old values. ```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 ``` -------------------------------- ### Triggering Client Notifications (Server-side, Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/ui/notifications.md Shows how to use the `TriggerClientEvent` function on the server-side to send a notification to a specific client using the 'ox_lib:notify' event. Requires the player's server ID ('source') and the ox_lib resource running on both client and server. Note that `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. ``` -------------------------------- ### Finding Closest Player and Vehicle (Lua) Source: https://github.com/4timci4/ox_lib-docss/blob/main/functions/closest-entity.md This snippet demonstrates how to use `ox_lib` functions to find the closest player (excluding the local player) and the closest vehicle to the player's current location. It retrieves coordinates, calls the respective `lib.getClosest` functions, and prints information about the found entities or indicates if none were found nearby. Requires the `ox_lib` library and access to game-specific entity functions. ```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 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.