Untitled conversation
- User
local icol = Color(255, 255, 255, 255) if CLIENT then local weapons = {"m9k_1887winchester", "m9k_1897winchester", "m9k_ares_shrike", "m9k_aw50", "m9k_barret_m82", "m9k_browningauto5", "m9k_contender", "m9k_dbarrel", "m9k_dragunov", "m9k_fg42", "m9k_intervention", "m9k_ithacam37", "m9k_jackhammer", "m9k_m3", "m9k_m24", "m9k_m60", "m9k_m98b", "m9k_m249lmg", "m9k_m1918bar", "m9k_minigun", "m9k_mossberg590", "m9k_psg1", "m9k_remington870", "m9k_remington7615p", "m9k_sl8", "m9k_svu", "m9k_usas", "m9k_spas12", "m9k_svt40", "m9k_striker12", "m9k_pkm"} for _, weapon in ipairs(weapons) do killicon.Add(weapon, "vgui/hud/" .. weapon, icol) end end local FCVAR_FLAGS = {FCVAR_REPLICATED, FCVAR_NOTIFY, FCVAR_ARCHIVE} local function CreateConfigVar(name, defaultValue, flags, description) if GetConVar(name) == nil then CreateConVar(name, defaultValue, flags, description) print(name .. " con var created") end end local configVars = {{"DebugM9K", "0", "Debugging for some m9k stuff, turning it on won't change much."}, {"M9KWeaponStrip", "0", "Allow empty weapon stripping? 1 for true, 0 for false"}, {"M9KDisablePenetration", "0", "Disable Penetration and Ricochets? 1 for true, 0 for false"}, {"M9KDynamicRecoil", "1", "Use Aim-modifying recoil? 1 for true, 0 for false"}, {"M9KAmmoDetonation", "1", "Enable detonatable M9K Ammo crates? 1 for true, 0 for false."}, {"M9KDamageMultiplier", "1", "Multiplier for M9K bullet damage."}, {"M9KDefaultClip", "-1", "How many clips will a weapon spawn with? Negative reverts to default values."}, {"M9KUniqueSlots", "1", "Give M9K Weapons unique slots? 1 for true, 2 for false. A map change may be required."}} for _, var in ipairs(configVars) do CreateConfigVar(var[1], var[2], FCVAR_FLAGS, var[3]) end if not game.SinglePlayer() then CreateConfigVar("M9KClientGasDisable", "0", FCVAR_FLAGS, "Turn off gas effect for all clients? 1 for yes, 0 for no.") if SERVER then local function ClientSideGasDisabler() timer.Create("ClientGasBroadcastTimer", 15, 0, function() BroadcastLua("RunConsoleCommand(\"M9KGasEffect\", \"0\")") end) end if GetConVar("M9KClientGasDisable"):GetBool() then ClientSideGasDisabler() end local function M9K_Svr_Gas_Change_Callback(cvar, previous, new) if tobool(new) then ClientSideGasDisabler() BroadcastLua("print(\"Gas effects disabled on this server!\")") else BroadcastLua("print(\"Gas effects re-enabled on this server.\")") BroadcastLua("print(\"You may turn on M9KGasEffect if you wish.\")") if timer.Exists("ClientGasBroadcastTimer") then timer.Remove("ClientGasBroadcastTimer") end end end cvars.AddChangeCallback("M9KClientGasDisable", M9K_Svr_Gas_Change_Callback) end if CLIENT then CreateConfigVar("M9KGasEffect", "1", {true, true}, "Use gas effect when shooting? 1 for true, 0 for false") end else CreateConfigVar("M9KGasEffect", "1", FCVAR_FLAGS, "Use gas effect when shooting? 1 for true, 0 for false") end local defaultVolume = 1.0 local defaultChannel = CHAN_ITEM local function addSound(soundData) if not soundData.name or not soundData.soundFile then return end sound.Add({ name = soundData.name, channel = soundData.channel or defaultChannel, volume = soundData.volume or defaultVolume, level = soundData.level or 75, pitch = soundData.pitch or {95, 110}, sound = soundData.soundFile }) end local function createSoundData(name, channel, soundFile) return { name = name, channel = channel, soundFile = soundFile } endOptimize the code and fix possible bugs, write a complete code implementation
- Assistant
Certainly! Below is the optimized and bug-fixed version of your Lua script for Garry's Mod (GMod) utilizing the M9K weapon base. This implementation addresses the incorrect handling of ConVar flags, improves code readability, ensures proper scope management, and includes necessary comments for clarity.
-- M9K Weapon Configuration and Setup -- Optimized and Bug-Fixed Version -- Define a white color for killicons local icol = Color(255, 255, 255, 255) -- List of M9K Weapon Class Names local weapons = { "m9k_1887winchester", "m9k_1897winchester", "m9k_ares_shrike", "m9k_aw50", "m9k_barret_m82", "m9k_browningauto5", "m9k_contender", "m9k_dbarrel", "m9k_dragunov", "m9k_fg42", "m9k_intervention", "m9k_ithacam37", "m9k_jackhammer", "m9k_m3", "m9k_m24", "m9k_m60", "m9k_m98b", "m9k_m249lmg", "m9k_m1918bar", "m9k_minigun", "m9k_mossberg590", "m9k_psg1", "m9k_remington870", "m9k_remington7615p", "m9k_sl8", "m9k_svu", "m9k_usas", "m9k_spas12", "m9k_svt40", "m9k_striker12", "m9k_pkm" } -- Killicon Setup (Client-Side) if CLIENT then for _, weapon in ipairs(weapons) do killicon.Add(weapon, "vgui/hud/" .. weapon, icol) end end -- Define ConVar Flags using bitwise OR local FCVAR_FLAGS = bit.bor(FCVAR_REPLICATED, FCVAR_NOTIFY, FCVAR_ARCHIVE) -- Function to Create a ConVar if it Doesn't Exist local function CreateConfigVar(name, defaultValue, flags, description) if not ConVarExists(name) then CreateConVar(name, defaultValue, flags, description) print("[M9K] ConVar created:", name) end end -- Configuration Variables local configVars = { {"DebugM9K", "0", "Debugging for some M9K stuff. Turning it on won't change much."}, {"M9KWeaponStrip", "0", "Allow empty weapon stripping? 1 for true, 0 for false"}, {"M9KDisablePenetration", "0", "Disable Penetration and Ricochets? 1 for true, 0 for false"}, {"M9KDynamicRecoil", "1", "Use aim-modifying recoil? 1 for true, 0 for false"}, {"M9KAmmoDetonation", "1", "Enable detonatable M9K Ammo crates? 1 for true, 0 for false."}, {"M9KDamageMultiplier", "1", "Multiplier for M9K bullet damage."}, {"M9KDefaultClip", "-1", "How many clips will a weapon spawn with? Negative reverts to default values."}, {"M9KUniqueSlots", "1", "Give M9K Weapons unique slots? 1 for true, 0 for false. A map change may be required."} } -- Create ConVars for _, var in ipairs(configVars) do CreateConfigVar(var[1], var[2], FCVAR_FLAGS, var[3]) end -- Gas Effect Configuration (Multiplayer Only) if not game.SinglePlayer() then -- Create 'M9KClientGasDisable' ConVar CreateConfigVar("M9KClientGasDisable", "0", FCVAR_FLAGS, "Turn off gas effect for all clients? 1 for yes, 0 for no.") if SERVER then -- Function to Disable Gas Effect on Clients local function ClientSideGasDisabler() timer.Create("ClientGasBroadcastTimer", 15, 0, function() for _, ply in ipairs(player.GetAll()) do ply:SendLua([[RunConsoleCommand("M9KGasEffect", "0")]]) end end) end -- Initial Check and Disable if Needed if GetConVar("M9KClientGasDisable"):GetBool() then ClientSideGasDisabler() end -- Callback Function for ConVar Changes local function M9K_Svr_Gas_Change_Callback(cvar, previous, new) local disable = tobool(new) if disable then ClientSideGasDisabler() BroadcastLua([[print("Gas effects have been disabled on this server!")]]) else BroadcastLua([[print("Gas effects have been re-enabled on this server.")]]) BroadcastLua([[print("You may turn on M9KGasEffect if you wish.")]]) if timer.Exists("ClientGasBroadcastTimer") then timer.Remove("ClientGasBroadcastTimer") end end end -- Add Change Callback cvars.AddChangeCallback("M9KClientGasDisable", M9K_Svr_Gas_Change_Callback) end if CLIENT then -- Define 'M9KGasEffect' ConVar with Appropriate Flags CreateConfigVar("M9KGasEffect", "1", bit.bor(FCVAR_ARCHIVE, FCVAR_USERINFO), "Use gas effect when shooting? 1 for true, 0 for false") end else -- Single Player: Define 'M9KGasEffect' ConVar with Standard Flags CreateConfigVar("M9KGasEffect", "1", FCVAR_FLAGS, "Use gas effect when shooting? 1 for true, 0 for false") end -- Sound Configuration local defaultVolume = 1.0 local defaultChannel = CHAN_ITEM -- Function to Add a Custom Sound local function AddSound(soundData) if not soundData.name or not soundData.soundFile then print("[M9K] Invalid sound data. 'name' and 'soundFile' are required.") return end sound.Add({ name = soundData.name, channel = soundData.channel or defaultChannel, volume = soundData.volume or defaultVolume, level = soundData.level or 75, pitch = soundData.pitch or {95, 110}, sound = soundData.soundFile }) end -- Function to Create Sound Data local function CreateSoundData(name, channel, soundFile, volume, level, pitch) return { name = name, channel = channel, soundFile = soundFile, volume = volume, level = level, pitch = pitch } end -- Example: Adding a Custom Sound (Uncomment and Modify as Needed) -- local myCustomSound = CreateSoundData("MyCustomSound", CHAN_WEAPON, "path/to/sound.wav", 1.0, 75, {100, 100}) -- AddSound(myCustomSound) -- Ensure to include this script as a shared file or place server/client specific code within appropriate folders.
Explanation of Optimizations and Fixes:
-
ConVar Flags Correction:
- Issue: originally,
FCVAR_FLAGSwas defined as a table, which is incorrect sinceCreateConVarexpects a bitwise combination of flag constants. - Fix: Utilized
bit.borto combineFCVAR_REPLICATED,FCVAR_NOTIFY, andFCVAR_ARCHIVEinto a single integer flag suitable forCreateConVar.
- Issue: originally,
-
Proper Scope Management:
- Ensured that server-specific operations (like creating timers and broadcasting Lua) are enclosed within
if SERVERblocks. - Similarly, client-specific operations (like adding killicons and creating client-side ConVars) are within
if CLIENTblocks.
- Ensured that server-specific operations (like creating timers and broadcasting Lua) are enclosed within
-
Improved
CreateConfigVarFunction:- Renamed
GetConVar(name) == niltonot ConVarExists(name)for better readability. - Added prefix
[M9K]to the print statement for clearer logging.
- Renamed
-
Gas Effect Handling in Multiplayer:
- Changed
BroadcastLuato target individual players usingply:SendLuafor better performance and control. - Ensured that the timer is removed if gas effects are re-enabled to prevent unnecessary broadcasting.
- Changed
-
Sound Configuration Enhancements:
- Enhanced the
AddSoundfunction to include error logging if required fields are missing. - Provided an example of how to create and add a custom sound, commented out for flexibility.
- Enhanced the
-
Code Readability and Comments:
- Added comprehensive comments to explain each section of the script.
- Organized the code into logical blocks for easier navigation and maintenance.
-
Safety Checks:
- Incorporated checks to ensure that essential fields (
nameandsoundFile) are present before adding a sound. - Used
tobool(new)to ensure the new ConVar value is correctly interpreted as a boolean.
- Incorporated checks to ensure that essential fields (
-
Modularity:
- Structured the code in a modular fashion, allowing for easy additions or modifications to the weapon list, ConVars, or sounds.
-
Example Usage:
- Provided an example (commented out) on how to create and add a custom sound, guiding future enhancements.
Usage Instructions:
-
Placement:
- Save this script as a shared Lua file (e.g.,
shared.lua) within your GMod addon directory. - Ensure that server-side and client-side scripts are correctly placed in their respective
lua/autorun/server/andlua/autorun/client/folders if you choose to split the script.
- Save this script as a shared Lua file (e.g.,
-
Customization:
- Killicons: Ensure that the killicon images are correctly placed in the
materials/vgui/hud/directory with filenames matching the weapon class names. - Sounds: Define and add custom sounds by uncommenting and modifying the example provided in the Sound Configuration section.
- ConVars: Adjust the default values and descriptions of ConVars as needed to fit your server's balance and preferences.
- Killicons: Ensure that the killicon images are correctly placed in the
-
Testing:
- After placing the script, restart your GMod server.
- Verify that killicons are appearing correctly, ConVars are created without errors, and that gas effects behave as configured.
- Test multiplayer scenarios to ensure that gas effects are being disabled or enabled as expected based on the
M9KClientGasDisableConVar.
-
Maintenance:
- Regularly update the weapon list and sound configurations as you add or remove weapons from your server.
- Monitor server logs for any potential issues or errors related to the script and address them promptly.
This optimized script should provide a more reliable and maintainable foundation for managing M9K weapons and related configurations in your GMod server. If you encounter any specific issues or have further requirements, feel free to ask!
-