Attempt to call a nil value ```math.lerp```

I got some of this code off of the Roblox assistant and I know the AI isn’t perfect but I cant seem to find a solution for this code here:

I’m trying to make a part spin whilst moving in a random direction within a given space.

in the while loop the math.lerp is getting a nil error. How can I fix this?

local Workspace = game:GetService("Workspace")
local part = Workspace.Part

local areaMin = Vector3.new(0, 0, 0)
local areaMax = Vector3.new(20, 20, 20)

local randomDirection = Vector3.new(
	math.random(areaMin.X, areaMax.X),
	math.random(areaMin.Y, areaMax.Y),
	math.random(areaMin.Z, areaMax.Z)
)

local startPosition = part.Position
local endPosition = randomDirection

local duration = 5  -- seconds
local startTime = tick()

while tick() - startTime < duration do
	local interpolationValue = (tick() - startTime) / duration
	local currentPosition = math.lerp(startPosition, endPosition, interpolationValue)
	part.Position = currentPosition
	wait()
end```
2 Likes

Yeah, the Studio assistant can give some code that doesn’t work a lot of the time. In short, math.lerp does not exist.

Here’s a lerping function you can use instead:

local function lerp(a: number, b: number, c: number): number
    return a + (b - a) * c
end

After a little bit of intense brain explosions I at least got your code to move the part.

local Workspace = game:GetService("Workspace")
local part = Workspace.Part

local areaMin = Vector3.new(0, 0, 0)
local areaMax = Vector3.new(20, 20, 20)

local randomDirection = Vector3.new(
	math.random(areaMin.X, areaMax.X),
	math.random(areaMin.Y, areaMax.Y),
	math.random(areaMin.Z, areaMax.Z)
)

local startPosition = part.Position
local endPosition = randomDirection

local duration = 5  -- seconds
local startTime = tick()

while tick() - startTime < duration do
	local interpolationValue = (tick() - startTime) / duration
	local currentPosition = part.CFrame.Position:Lerp(endPosition, interpolationValue)
	part.CFrame = CFrame.new(currentPosition)
	wait()
end

Try this and see what you think. I am a noob with lerp but at least I did something with it

its supposed to spin the part and move it in a random direction within a certain space. My brain isn’t braining.

1 Like

I think that should be startPosition:Lerp(endPosition, interpolationValue)

1 Like