vRP-framework / vRP

FiveM (http://fivem.net) RP addon/framework
https://vrp-framework.github.io/vRP
MIT License
294 stars 191 forks source link

Restarting scripts #656

Open jaimeadf opened 2 years ago

jaimeadf commented 2 years ago

The missing ability to restart scripts on the fly seems to keep some developers away from developing for vRP 2. This got me thinking of what could be done to implement this feature and still maintain compatibility. So, I've done a little research and I would like to share it.

Firstly, the main challenges I identified are:

Threads

My idea is to keep track of all the thread ids to terminate them using TerminateThread when the resource is stopped. The lua load function allows us to use a custom environment when executing a code and, therefore, lets us override the methods. For example:

local custom_environment = {
    print = print,
    MESSAGE = "Hello, this is an overridden global variable."
}

-- Loads the code with the custom environment.
local execute = load([[ print(MESSAGE) ]], "code.lua", "bt", custom_environment)

execute()

With that in mind, I've made a small sample of how it could be implemented.

-- Creates table to keep track of the threads created by the script.
local thread_ids = {}

-- Wraps the FiveM's CreateThread and inserts the id to 'thread_ids' for every new thread.
function TrackedCreateThread(handler)
    CreateThread(function (id)
        table.insert(thread_ids, id)
        handler()
    end)
end

-- Declares an environment that overrides the 'CreateThread' to call 'TrackedCreateThread' instead.
local custom_environment = setmetatable(
    { CreateThread = TrackedCreateThread },
    { __index = _ENV }
)

-- Loads the code using the custom environment.
local execute = load(code, file, "bt", custom_environment)

execute()

-- When the resource is stopped, terminate all threads.
for index, thread_id in ipairs(thread_ids) do
    TerminateThread(thread_id)
end

A similar approach could be done to the events.


Sadly, I don't have many ideas to solve the other issues. Though, I'd love to hear some feedback and know what you guys think and solutions to the other challenges.

By the way, I am aware that this is a duplicate of #516, but I've decided to keep it separate.