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

Why does it error if I do not return the new part?

Before I start, I want to say that I did not make this script, I got it from "The Power of CFrames" guide.

Error: ServerScriptService.Script:17: attempt to index local 'lastPart' (a nil value)

I know this error is coming from not returning it.

Basically I am asking, why does it not error when we make the part the first time?"

Here is the script:

local start = Instance.new("Part", workspace)
start.CFrame = CFrame.new(0, 10, 0)
start.Anchored = true


local slowness = .1
local useSlow = true


local function newPart(lastPart, angle, slow)
	local function doWait() -- This function will add pauses to the CFraming so we can understand it more.
		if slow then
			wait(slowness)
		end
	end
	
	local new = lastPart:Clone()
	new.Parent = workspace
	new.CFrame = lastPart.CFrame
	
	doWait()
	
	new.CFrame = new.CFrame * CFrame.new(new.Size.X/2, 0, 0)
	
	doWait()
	
	new.CFrame = new.CFrame * CFrame.Angles(0, 0, math.rad(angle))
	
	doWait()
	
	new.CFrame = new.CFrame * CFrame.new(new.Size.X/2, 0, 0)
	
	--return new
end

for angle = 10, 360, 10 do
	start = newPart(start, 10, useSlow)
end

1 answer

✓ Accepted answer

On line 1, you create a Part, and assign the variable start to it:

local start = Instance.new("Part", workspace)

Further down, on line 36, you have this loop:

for angle = 10, 360, 10 do
	start = newPart(start, 10, useSlow)
end

In English, the above code is "Counting up from 10 to 360, incrementing by 10, call the newPart function with the arguments start, 10, and useSlow, and set start to the return value."


The reason it doesn't work without the return is because of that last part, "set start to the return value." With the return, start becomes the part which new referenced within the function. Without, start becomes nil.

Looking back at the English representation of the loop, we see that you "call the newPart function with the arguments start, 10, and useSlow." As a result, if you don't return the new part, start becomes nil, so on the next iteration start is nil. So, your call becomes:

start = newPart(nil, 10, true)

To wrap up, the reason you get your error,

ServerScriptService.Script:17: attempt to index local 'lastPart' (a nil value)

is because on line 17,

local new = lastPart:Clone()

lastPart becomes nil, and you attempt to call Clone on it.

But, of course, this shouldn't be a problem; all you have to do is leave in the return and it'll work just fine!

Hope this helped.

1 comment

0

Thanks, it helped a lot.

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