๐Ÿš€Script Optimization

Learn how to write optimized code!

General Practices

  • Localize as many functions and variables as possible. Lua can read them faster

myVariable = false -- Don't use this
local myVariable = false -- Use this

function someFunction() -- Don't use this
    print('Im a global function!')
end

local function someFunction() -- Use this
    print('Im a local function!')
end
  • Instead of using table.insert use tableName[#tableName+1] = data

function someFunction()
    local table = {}
    table.insert(table, {}) -- Don't use this
    table[table+1] = {} -- Use this
end
  • Instead of using if something ~= nil use if something then. This method checks for nil and/or false at the same time

  • If you are creating a function or an event, make it so that it can be used in different scenarios with different variables. Keep it universal basically

  • When writing code use what's known as "short returns" for failed conditions


Native Usage

  • Always replace GetPlayerPed(-1) with PlayerPedId()

  • Always replace GetDistanceBetweenCoords with lua math aka #(vector3 - vector3)


Loops

  • Control your while loops and when they run

  • If you do have to create a thread that includes a "while" loop, always avoid using "while true do" if able. If you have to use this, follow the next tip, and it wonโ€™t impact performance as much

  • Control your thread times by using a variable that changes the wait time retroactively. So you can set the thread wait time to say 1000ms which checks for your if statement every second and if it makes it into the statement you can lower the wait time by just changing the variable value. Wait(sleep)

  • If you have job specific loops, make sure they only apply to players with that job. There's no reason for someone who is not a cop to be running a loop on their machine that does not apply to them


Security

  • A surplus amount of security in a code is not a bad thing. Don't be afraid to add in multiple if checks or create random variables to pass through your events

  • Never do any type of transaction with the player regarding money or items on the client side of a resource

Event Handlers

  • When setting variables inside your resource, handlers come in especially handy due to not needing to constantly run checks

Last updated