Is there any way I can improve my local laser script and/or module?

Hi, I’m wondering if I can make my code even better. I am already satisfied with my code but I do think it could be even better. I want to pay a lot of attention to performance.

Local script under StarterPlayerScripts:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local ModuleScripts = ReplicatedStorage.ModuleScripts

local LaserModule = require(ModuleScripts.LaserModule)

for _, Descendant in pairs(workspace:GetDescendants()) do
	
	if Descendant.Name == "Laser" then
		
		LaserModule.InsertLaser(Descendant)
	end
end

local RunService = game:GetService("RunService")

local function RenderStepped()
	
	LaserModule.RaycastLasers()	
end

RunService.RenderStepped:Connect(RenderStepped)

ModuleScript under ReplicatedStorage:

local LaserModule = {}

local Lasers = {}

function LaserModule.InsertLaser(Laser)
	
	if not table.find(Lasers, Laser) then
		
		table.insert(Lasers, Laser)
	end
end

function LaserModule.RaycastLasers()
	
	for _, Laser in pairs(Lasers) do
		
		local Attachment0 = Laser:FindFirstChild("Attachment0")

		local Attachment1 = Laser:FindFirstChild("Attachment1")

		if Attachment0 and Attachment1 then

			local RaycastParams = RaycastParams.new()

			RaycastParams.IgnoreWater = false

			local RaycastResult = workspace:Raycast(Attachment0.WorldPosition, Laser.CFrame.LookVector * 10)

			if RaycastResult then

				Attachment1.WorldPosition = RaycastResult.Position

				print(RaycastResult)

			else

				Attachment1.Position = Attachment0.CFrame.LookVector * 10
			end
		end		
	end
end

return LaserModule
  1. You do not have to insert a newline after every line.
  2. You can use OOP and give the laser its own class.
1 Like

I work alone and like to use whitespace. Could you please explain what ‘‘OOP’’ is?

See All about Object Oriented Programming for OOP in Lua.

1 Like