Garry's Mod Wiki

Understanding AddCSLuaFile and include

Introduction

AddCSLuaFile and include are two essential functions in Garry's Mod Lua scripting, facilitating script management across server and client. Understanding their usage is crucial for efficient Garry's Mod development.

AddCSLuaFile

  • Purpose: Tells the server to send specified Lua files to the client. Essential for clientside script execution.
  • Common Use: In a serverside script (e.g init.lua), to ensure clients receive and can execute client and shared files. Example:
if SERVER then AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") end

include

  • Purpose: Executes the content of a Lua file from another Lua script. Used for code modularity and reuse.
  • Usage: Both server and client can use include to incorporate and execute the content of another Lua file.
include("shared.lua")

General Usage

Server Scripts (init.lua): Used to set up server specific logic, AddCSLuaFile is called for clientside scripts, while include integrates shared or serverside scripts.

AddCSLuaFile("cl_init.lua") include("shared.lua")

Client Scripts (cl_init.lua): Dedicated to clientside functionality, automatically run on the client post AddCSLuaFile. Integrates shared logic through include.

include("shared.lua")

Shared Code (shared.lua): Contains code used by both client and server. It's included in both init.lua and cl_init.lua.

Key Points

  • init.lua and cl_init.lua are implicitly executed by the server and client (if they are located in the correct places Lua_Folder_Structure), respectively, assuming cl_init.lua has been sent to the client. Using these functions correctly ensures scripts are executed in the appropriate context (server or client) and facilitates code organization and reuse.

Diagram

The diagram illustrates two separate entities: a client and a server, each with its own execution context. When the server dispatches the clientside Lua file to the client, the transfer of that specific file is complete. Meanwhile, within its own execution context, the server progresses to execute the subsequent code.