Skip to content

ServerExample

JabDoesThings edited this page Nov 17, 2024 · 1 revision
local ModLoader = require 'asledgehammer/modloader/ModLoader';

if not isServer() then return end

(function()

    local module = 'FoobarExample';
    local info = function(msg)
        print('[' .. module .. '] :: ' .. msg);
    end

    local notFound = function(module, path)
        info(
            'File not installed: Zomboid/Lua/ModLoader/mods/' 
            .. module .. '/' .. path
        );
    end

    local onServerStart = function()

        -- Load the client-side code and cache it as encrypted.
        ModLoader.requestServerFile(

            -- File: '~/Zomboid/Lua/ModLoader/mods/FoobarExample/FoobarExample_Client.lua'
            module,
            'FoobarExample_Client.lua',
            
            -- Cache this result for clients as to not grab the file again.
            -- (If the file is dynamic, set to false)
            true,

            -- The callback function.
            function(module, path, result, data)
                
                -- Handle the RESULT_FILE_NOT_FOUND situation.
                if result == ModLoader.RESULT_FILE_NOT_FOUND then
                    notFound(module, path);
                    return;
                end

                -- No need to do anything else because the file is cached
                -- and ready to serve.
        end);

        -- Load the server-side code and run it.
        ModLoader.requestServerFile(
            -- File: '~/Zomboid/Lua/ModLoader/mods/FoobarExample/FoobarExample_Server.lua'
            module,
            'FoobarExample_Server.lua',
            -- No need to cache the file. It only runs once.
            false, 
            
            -- The callback function.
            function(module, path, result, data)
            
                -- Handle the RESULT_FILE_NOT_FOUND situation.
                if result == ModLoader.RESULT_FILE_NOT_FOUND then
                    notFound(module, path);
                    return;
                end

                -- Load and run the code.
                loadstring(data)();
                info('Successfully loaded file: ' module .. '/' .. path);

            end);
        end

    end

    Events.OnServerStarted.Add(onServerStart);
end)();

Clone this wiki locally