Esc to clear, Enter to open the best match, click an export to open it in its page
Vehicles

Vehicle stats API

A vehicle stat is a number a car carries: fuel, nitrous, wear, boost. Register it once and WHIP saves it, replicates it to everyone in the car, draws its gauge and checks what clients report.

Registering a stat

RegisterVehicleStat(name, config)SERVER#

Register a stat every vehicle can carry. It's saved with the car and replicated to everyone sitting in it. A hud block makes it a gauge around the rev dial (five at most are shown, by order).

FieldTypeDescription
defaultnumberWhat a vehicle starts on
min / maxnumberIts range
persistboolean|stringtrue (default): the value survives a restart. false: nothing does. 'presence': that the car has it, at its fitted value; written only when it appears or goes, for live fittings such as a turbo
decaynumber?Points changed every decayInterval; negative drains. Leave it out to disable: 0 still ticks
decayIntervalnumber?Seconds between decay steps. Default 10
hudtable?{ label, icon, color, order, iconOnly, showAboveZero, showWhenPresent, hideWhenEmpty, noCritical }. icon: an SVG path in a 24x24 box; order: lower first (fuel is 1); below 20% it flashes red unless noCritical. The dial draws gauges white, so color isn't used there; an iconOnly stat (an on/off light) gets no gauge
consumetable?{ maxRate, driverOnly, clearAtMin, interval, slack }: the client reports what it used. See consume and live
livetable?{ maxRate, driverOnly, interval, slack }: the client reports the current value
displaytable?How the value reads on its gauge and in /whip, instead of a percentage: { unit = 'psi', range = { -3, 30 } } (what min and max read); { unit = '°C', points = { { 0, 20 }, { 50, 90 }, { 100, 130 } } } (a curve, percent of range to reading); { ends = { 'E', 'F' } } (end labels, no number); decimals 0-2. The stat's range is unchanged
Returns: boolean, string|nil: ok, and why not
Whip.register(function()
    Whip.core:RegisterVehicleStat('nos', {
        default = 0, min = 0, max = 100,
        hud = { label = 'NOS', icon = 'M6 2h6v20H6z', color = '#60a5fa', order = 2 },
    })
end)
-- later, once a car has a bottle fitted
exports.whip_core:AddVehicleStat(vehicleId, 'nos', -10, 'mynos:boost')
clearAtMin requires default == min, or registration is refused: a cleared stat reads as its default, so it would refill itself by running out. Use it for installables, not for something every car has, like fuel.

Reading and writing

GetVehicleStat / SetVehicleStat / AddVehicleStat / GetVehicleStatsSERVER#

Read and write stats. Writes are clamped to the stat's range, saved and replicated. GetVehicleStat and GetVehicleStats also work on the client, for a car streamed in nearby.

ParamTypeDescription
vehicleIdnumber|tableA vehicle reference
namestringA registered stat name
value / deltanumberWhat to set it to, or add to it
changeSourcestring?A label for the change, e.g. 'refuel:pump'
Returns: GetVehicleStat → number|nil; GetVehicleStats → { [name] = value }, defaults filled in (stored only: below); writes → boolean, string|nil (no such car, not a number, unregistered stat)
exports.whip_core:SetVehicleStat(vehicleId, 'fuel', 100.0, 'refuel:pump')
SetVehicleStats(vehicleId, values, changeSource)SERVER#

Write several stats to one car in a single replication: fitting a kit, resetting a car. Each single write re-sends the car's whole block.

ParamTypeDescription
vehicleIdnumber|tableA vehicle reference
valuestable{ [statName] = value }: unregistered names and non-numbers are skipped and logged
changeSourcestring?A label for the change events
Returns: number written, or false, reason when none took
HasVehicleStat(vehicle, name)CLIENTSERVER#

Does this car actually carry the stat, rather than read as its default? Use it whenever you mean "is one fitted". In a loop, prefer WatchVehicleStat.

ParamTypeDescription
vehiclenumber|tableA vehicle reference
namestringRegistered stat name
Returns: boolean
GetVehicleStat(veh, name) > 0 isn't the same. An absent stat reads as its default, so a stat resting above zero would read as fitted on every car.
GetVehicleStats(vehicleId, { stored = true })SERVER#

Only the stats a car actually stores, no defaults: nil for an installable means not fitted. The vehicle-list payloads send this, so a garage card can tell a spent bottle from none.

ParamTypeDescription
vehicleIdnumber|tableA vehicle reference
opts.storedbooleantrue: stored values only
Returns: { [name] = value }, a copy; empty for an unknown vehicle
ClearVehicleStat(vehicleId, name)SERVER#

Take a stat off one car: the part comes off. Reads fall back to the default, and the change is announced with cleared = true. It also resets a live stat's rate check, so a refit starts from idle.

ParamTypeDescription
vehicleIdnumber|tableA vehicle reference
namestringRegistered stat name
Returns: boolean, string|nil: true includes already absent; false with the reason (no such vehicle, a bad name)
Setting it to zero isn't the same. Zero leaves the stat on the car (a bottle fitted and empty); this is the only call that removes it.
PurgeVehicleStat(name)SERVER#

Delete a stat's values from every car, for good, each as ClearVehicleStat does: for retiring a stat. Stopping a resource never does this, so a restart never wipes a fitted part.

ParamTypeDescription
namestringThe stat to retire
Returns: number of cars that had a value, or false, reason when another running resource registered it (anyone may purge a stat with no running owner)
ClearVehicleDamage(vehicle)SERVER#

Forget the damage a car keeps, so its next spawn is like new. Call it with a repair: it doesn't fix the car in the world, which only the game running it can do.

ParamTypeDescription
vehiclenumber|tableA vehicle reference
Returns: boolean, string|nil (no such vehicle)

Listening for changes

OnVehicleStatChanged(name, callback, id, opts)SERVER#

Be called when one stat changes, on any car, yours or another resource's. Declare it in Whip.register with your stats, so it comes back after a whip_core restart; it's dropped when your resource stops.

ParamTypeDescription
namestringA stat's name, or '*' for every stat (server only, and the costly one)
callbackfunction(vehicleId, value, previous, cleared, source); for '*', (vehicleId, name, value, previous, cleared, source); or one table with table = true (change.key is the stat)
idany?Only for two listeners on one stat; the same id replaces
optstable?{ table = true, now = true }; may go third. now reports every car carrying the stat at once, with source = 'now'. now = 'all' (named stat) visits every car WHIP has, defaults included, for decisions from the value (an engine hold); registering again after the default changed visits them again
Returns: boolean registered
exports.whip_core:OnVehicleStatChanged('fuel', function(change)
    -- change.vehicleId, change.key, change.value, change.old, change.cleared, change.source
end, { table = true, now = true })
The callback must not wait. It runs inside the stat write: put slow work (a database write) in a CreateThread.
OnVehicleStatChanged(name, callback, id, opts)CLIENT#

Be called when a stat's value changes on any car in scope. Use it for the number; use WatchVehicleStat for a car having the stat. Takes the server's table and now options, third or after an id.

ParamTypeDescription
namestringRegistered stat name
callbackfunction(vehicleId, value, old, entity), or with table = true: { vehicleId, key, value, old, cleared, entity }
Returns: boolean registered

Reacting to a stat: WatchVehicleStat#

WatchVehicleStat runs your code while a car carries a stat. WHIP is already told when a stat appears or goes on any car in scope, so you never poll or cache. Pick the right pair of callbacks:

onGained / onLostonStart / onStop
Tells youwhat's true in the worldwhat this watcher is doing
Fires forevery car in scope, ignoring driverOnlyonly what whileHeld runs for
Getting outnothing: the car still has itonStop
Use fora badge, a sound, an effect on any car nearbysetting up and undoing your own work

If you change a car and must put it back, use onStart/onStop: onStop covers getting out, losing the stat, the car despawning and the part being pulled. Set driverOnly for anything touching handling or physics: you only own the car you drive.

-- A turbo resource, in full: no loop, no cache
exports.whip_core:WatchVehicleStat('boost', {
    onStart   = function(entity)             captureHandling(entity) end,
    whileHeld = function(entity, value, dt) simulate(entity, dt)     end,
    onStop    = function()                   restoreHandling()        end,
    interval   = 50,     -- ms between whileHeld calls; 0 is every frame
    driverOnly = true,
})

-- The one end onStop never hears: this resource stopping. restoreHandling must be safe twice.
AddEventHandler('onResourceStop', function(res)
    if res == GetCurrentResourceName() then restoreHandling() end
end)
Start interval at 50. 0 runs every frame: 120 calls a second at 120 fps. A resource without dependency 'whip_core' also restores in Whip.onCoreLost.
WatchVehicleStat(name, data)CLIENT#

Run code while a car in scope carries a stat. Cars already carrying it are announced on registration. name may be a list: then every callback gets the stat's name second (onGained(entity, name, value)), and one id covers them all.

FieldTypeDescription
onGainedfunction?(entity, value): a car in scope gained the stat
onLostfunction?(entity): a car in scope lost it
onStartfunction?(entity, value): whileHeld is about to run for this car
onStopfunction?(entity): whileHeld stopped for this car
whileHeldfunction?(entity, value, dt), repeatedly; dt is real seconds, a stall clamped to 0.25 s (or twice your interval). Return a number to show it on this client's gauge until onStop
intervalnumber?ms between whileHeld calls. Default 0 (every frame)
driverOnlybool?Narrow whileHeld, onStart, onStop to the car you drive. Default false
Returns: string|false, string|nil: watcher id, or false and why (a bad name or table)
With a list, whileHeld runs once per stat. For one job per car, track what's fitted with onStart/onStop and run your own loop only while something is.
UnwatchVehicleStat(watcherId)CLIENT#

Stop one of your watchers. Fires onStop for what it was running, not onLost. Watchers also go when their resource stops.

ParamTypeDescription
watcherIdstringThe id from WatchVehicleStat; a list's id stops every stat in it
Returns: boolean removed
SetVehicleStatWatchInterval(watcherId, ms)CLIENT#

Change how often one of your watchers' whileHeld runs. 0 is every frame; tens of milliseconds is plenty for most.

ParamTypeDescription
watcherIdstringThe id from WatchVehicleStat; a list's id sets every stat in it
msnumberMilliseconds between runs
Returns: boolean: false for the same interval again, or an id that isn't yours

Stats the client drives: consume and live#

Some values only the client knows: nitrous burned, boost, engine heat. A stat declared consume or live lets the client report them, and WHIP does the rest: one batched event per car, the driver check (driverOnly, default true), and a cap measured against the wall clock, so a modified client gets the same ramp as an honest one. A report lost to the rate limit costs nothing: the next carries the current picture.

consumelive
The valueonly fallsrises and falls
Client reportshow much was usedwhat it's worth now
Client callsConsumeVehicleStat, ConsumeVehicleStatsReportVehicleStat
Server capshow fast it drainshow fast it rises
Forfuel, nitrous, tyre wearturbo boost, engine heat, charge
FieldDefaultMeaning
maxRaterequiredUnits per second, flat out: the ceiling the server believes
driverOnlytrueOnly the driver may report
interval1.0 / 0.5 sHow often the client sends (consume / live); at least 0.25 s
slack1.25Headroom over maxRate for network jitter
clearAtMinfalseconsume only: take the stat off the car when it bottoms out
-- Server: declare it. Nothing else handles the reporting.
exports.whip_core:RegisterVehicleStat('boost', {
    default = 1, min = 1, max = 100,
    persist = 'presence',                       -- the turbo is fitted; the number is momentary
    live = { maxRate = 33.3, interval = 0.25 }, -- nothing to full in three seconds
    hud  = { label = 'Boost', color = '#facc15', order = 6, showWhenPresent = true },
})

-- Client: work out the value, and say what it is
exports.whip_core:ReportVehicleStat({ entity = veh }, 'boost', level)
ReportVehicleStat(vehicle, name, value)CLIENT#

Tell WHIP what a live stat is worth now. The newest value wins and is sent at the stat's interval; the server caps how fast it rises.

ParamTypeDescription
vehiclenumber|tableA vehicle reference
namestringA stat registered with live
valuenumberWhat it's worth now
Returns: boolean: whether the value was taken
Not every frame. Each call costs about 20µs. Call when the value has moved by enough, no more often than interval, and compare on difference so a refused send is retried and the final value gets across.
ConsumeVehicleStat(vehicle, name, delta)CLIENT#

Report that this client used some of a consume stat. Deltas add up locally and the total is sent at the stat's interval. Safe every frame; for several stats, use ConsumeVehicleStats.

ParamTypeDescription
vehiclenumber|tableA vehicle reference
namestringA stat registered with consume
deltanumberAmount used since the last call; positive
Returns: boolean: false when the vehicle didn't resolve or the delta wasn't positive
It doesn't check the tank. The server clamps at the minimum; to stop at empty, read GetVehicleStat yourself.
ConsumeVehicleStats(vehicle, deltas)CLIENT#

Report several stats used on one car in a single call: the same as ConsumeVehicleStat for each, at a fraction of the cost.

ParamTypeDescription
vehiclenumber|tableA vehicle reference
deltastable{ [statName] = amountUsed } since the last call, positive
Returns: boolean ok, number accepted
Check ok, not the count. (true, 0) means nothing in the table was usable; (false, 0) means the vehicle didn't resolve.

Gauges

These change only this player's dial, never the stat. Each stat has one rule, its setter's, dropped when that resource stops.

SetVehicleStatDisplay(name, fn)CLIENT#

Draw a local reading for a stat on this client's gauges instead of the replicated one, for a value you compute in real time. It changes the number, never whether the gauge shows. Without a watcher the needle moves about once a second; with one, after each whileHeld tick.

ParamTypeDescription
namestringRegistered stat name
fnfunction(entity, replicated) → a number, or nil for the replicated value
Returns: true, or false, reason when another resource provides this stat
exports.whip_core:SetVehicleStatDisplay('boost', function(entity, replicated)
    if entity ~= myTunedVehicle then return nil end   -- passengers get the replicated value
    return liveBoost
end)
Running a watcher? Return the reading from whileHeld instead: it's cheaper and wins over a provider.
ClearVehicleStatDisplay(name)CLIENT#

Stop drawing your local reading; the gauge shows the replicated value again.

Returns: true, or false, reason (not set, or another resource's)
SetVehicleStatShown(name, fn) · ClearVehicleStatShown(name)CLIENT#

Whether a stat's gauge is drawn on a car. fn(entity) returns false to hide it; it's asked once per car the player sits in, so answer from what the car is.

Returns: true, or false, reason (no name or rule, or another resource's rule)
exports.whip_core:SetVehicleStatShown('fuel', function(entity)   -- no fuel gauge on an electric car
    return not exports.whip_core:IsVehicleElectric({ entity = entity })
end)
SetVehicleStatIcon(name, fn) · ClearVehicleStatIcon(name)CLIENT#

A stat's gauge icon per car. fn(entity) returns one of the dial's icons ('fuel', 'fuel_left', 'fuel_right', 'turbo', 'nitro', 'coolant', 'hack', 'weapon'), an SVG path in a 24x24 viewBox, or nil for the stat's own. Asked once per car.

Returns: true, or false, reason (no name or rule, or another resource's rule)
exports.whip_core:SetVehicleStatIcon('fuel', function(entity)   -- point to the filler's side
    local p = exports.whip_core:GetVehiclePoint({ entity = entity }, 'fuel')
    if p and p.fixed and p.side == 'left' then return 'fuel_left' end
end)