Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I "define" a variable that is already said earlier in the code?

I have this script for aiming down a scope for a shooter game. in one of the if else functions I get an error that reads: attempt to index nil with 'aimSmooth'. This issue only occurs for the second time that is stated.

Code:

RunService.RenderStepped:Connect(function()
	
	local rot = camera.CFrame:ToObjectSpace(lastCameraCF)
	local X,Y,Z = rot:ToOrientation()
	swayCF = swayCF:Lerp(CFrame.Angles(math.sin(X) * currentSwayAMT, math.sin(Y) * currentSwayAMT, 0), .1)
	lastCameraCF = camera.CFrame
	
	local humanoid = character:WaitForChild("Humanoid")
	
	if humanoid then
		local bobOffset = CFrame.new()
		
		if humanoid.MoveDirection.Magnitude > 0 then
			if humanoid.WalkSpeed == 13 then
				bobOffset = bobOffset:Lerp(CFrame.new(math.cos(tick() * 10) * .2, -humanoid.CameraOffset.Y/3, -humanoid.CameraOffset.Z/3), .1)
				end

			elseif humanoid.WalkSpeed == 20 then
				bobOffset = CFrame.new(math.cos(tick() * 18) * .3, -humanoid.CameraOffset.Y/3, -humanoid.CameraOffset.Z/3)
			end
		
		else
			 bobOffset = bobOffset:Lerp(CFrame.new(0, -humanoid.CameraOffset.Y/3, 0), 0)
		end
		
		for i, v in pairs(camera:GetChildren()) do
			if v:IsA("Model") then
				v:SetPrimaryPartCFrame(camera.CFrame * swayCF * aimCF * bobOffset)
			end
		end
	end)
	
	if isAiming and framework.viewmodel ~= nil and framework.module.canAim then
		local offset = framework.viewmodel.AimPart.CFrame:ToObjectSpace(framework.viewmodel.PrimaryPart.CFrame)
		aimCF = aimCF:Lerp(offset, framework.module.aimSmooth)
		currentSwayAMT = aimSwayAMT
	else
		local offset = CFrame.new()
		aimCF = aimCF:Lerp(offset, framework.module.aimSmooth)
		currentSwayAMT = swayAMT
end

Line 39 is the code in question, right under the first time it was mentioned (line 35). Line 35 works just fine still.

For more info, the following code is a module script that supports this one. The code is to change the speed and smoothness of the aiming system.

local Settings = {
	
	canAim = true;
	aimSmooth = .07;
	
}

return Settings

1 answer

Im not the smartest coder but I think you can just

reinstate it

like local Settings = {. can be local Settings = }.

This discussion is preserved as it was. New answers, comments, and votes are closed.