How can I better organize my code?

I have been coding for 3 years now and I would say that I am a pretty good scripter, I am even taking on a huge project myself. Now I’m not worried about this huge project, I know I am perfectly capable of making it, my only issue is organization, something I never really learned how to do. I believe that every game has so many different things that need to be handled like money, gui, sounds, etc. I just want to know how to properly organize my scripts and the code within them.

I threw together this example script (I know it looks long, but it really isn’t), it has nothing to do with any game I have worked on, but it demonstrates my basic layout of code:

-- Vars -- 
local _replicatedStorage = game:GetService("ReplicatedStorage")
-- Some other services

local _rmEvent = _replicatedStorage:WaitForChild("RemoteEvent")

local _moduleScript = script:WaitForChild("module") -- I'd usually give it a more creative name
-- Maybe some other modules

local _cash = 0
-- Some other global variables

-- Functions --
function purchase(item)
	local price = _moduleScript.getPrice(item)
	if (_cash >= price) then
		_cash -= price -- I would usually do this on the server, but this is an example, I'm not stupid
function onStart()
	_cash = _rmEvent:FireServer()
	-- Some other stuff I might do on start
-- Some other functions

-- Events --
-- I might set some other events here

As for my placement of scripts, I usually have all my local scripts in StarterPlayerScripts and ReplicatedFirst and then I’ll have my server scripts in ServerScriptStorage.

How might I organize my code a little better so that it is easier to work with? Thanks

It looks good to me. However, I do not recommend that you use _ as the first character for variables, especially global variables. Because other people would think that it is a private variable, which means you don’t want other people to actually access this variable.

You could also use frameworks such as knit that allow the client and server to communicate easily, and you are also able to modify the code. If you want you could use this runtime that I made.

Edit: I just notice wouldn’t this be better to be on #help-and-feedback:code-review

1 Like

I use underscores to easily identify global variables vs local variables. Also, I would disagree that my code ‘looks goods’ because after a month of coding a game, I have one function doing something that another function is already doing, but just different enough that I can’t reuse it. I just keep adding functions and more functions until debugging comes around and I spend 600 hours trying to find the problem.

If you want to make global variables and easily identify that it is a global variable, it’s better if you all caps the variable name.

If so, then why not create a function that does what the two functions do and return them?