Garry's Mod Wiki

Revision Difference

Understanding_AddCSLuaFile_and_include#561603

<cat>Dev.GettingStarted</cat> <title>Understanding AddCSLuaFile and include</title> ## Introduction <page>Global.AddCSLuaFile</page> and <page>Global.include</page> 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: ```lua 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 <page>Global.include</page> to incorporate and execute the content of another Lua file. ```lua include("shared.lua") ``` ------------ ### General Usage Server Scripts (init.lua): Used to set up server specific logic, <page>Global.AddCSLuaFile</page> is called for clientside scripts, while include integrates shared or serverside scripts. ```lua AddCSLuaFile("cl_init.lua") include("shared.lua") ``` Client Scripts (cl_init.lua): Dedicated to clientside functionality, automatically run on the client post <page>Global.AddCSLuaFile</page>. Integrates shared logic through <page>Global.include</page>. ```lua 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 <page>Lua_Folder_Structure</page>), 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. ⤶ <upload src="b5453/8dc301d69874605.png" size="71692" name="image.png" />⤶ <image src="b5608/8dc519b90c767b5.png" size="193641" name="Diagram.png" />