robloxluau

Fix "attempted to call a nil value" in roblox lua


I'm making a ModuleScript that uses properties from a vehicleSeat and even though the seat does exist and studio shows me the properties I'm trying to read, I get "attempted to call a nil value" with no reference to where it happened in the code. I'm reading the MaxSpeed, Torque, ThrottleFloat ,SteerFloat, and TurningSpeed properties

I've broken down the code and for some reason the error starts when I read from steering and throttle.

I've made a test server script that read the steering and throttle and sum reason that one works yet I got this script working before in a module script.

I also tried passing the properties as function parameters and it still happens.

It does work if I pass a number though.

Heres the code

local Controller = require(script.Parent.BasicSedanDoorController)
Controller.DriverSeat.Changed:Connect(Controller.Drive())
local Controller = {}
vehicle = script.Parent
Controller.DriverSeat = vehicle.body.DriverSeat.VehicleSeat
suspension = vehicle.Suspension
turningRadius = 45
Parts = {
    Steering = {
        FL = suspension.FrontLeftArm.Hub.CylindricalConstraint,
        FR = suspension.FrontRightArm.Hub.CylindricalConstraint
    },
    driveTrain = {
        RL = suspension.RearLeftArm.Hub.MotorConstraint,
        RR = suspension.RearRightArm.Hub.MotorConstraint
    },
    Lights = {
    }
}
topSpeed = Controller.DriverSeat.MaxSpeed
Parts.driveTrain.RL.MotorMaxTorque = Controller.DriverSeat.Torque
Parts.driveTrain.RR.MotorMaxTorque = Controller.DriverSeat.Torque 
Parts.Steering.FL.AngularSpeed = Controller.DriverSeat.TurnSpeed
Parts.Steering.FR.AngularSpeed = Controller.DriverSeat.TurnSpeed
Parts.Steering.FL.ServoMaxTorque = 1000000
Parts.Steering.FR.ServoMaxTorque = 1000000
function Controller.DoorController(door:Model)
    local servo: HingeConstraint = door:WaitForChild("Exterior"):WaitForChild("Servo")
    if servo.TargetAngle == 180 then
        servo.TargetAngle = 120
    else
        servo.TargetAngle = 180
    end
end
function Controller.Drive()
    Parts.Steering.FL.TargetAngle = Controller.DriverSeat.Steer
    Parts.Steering.FR.TargetAngle = Controller.DriverSeat.Steer
    Parts.driveTrain.RL.AngularVelocity = Controller.DriverSeat.Throttle
    Parts.driveTrain.RR.AngularVelocity = Controller.DriverSeat.Throttle
end
return Controller

Solution

  • The error is telling you that something is trying to call a function that doesn't exist. So let's focus on this line :

    Controller.DriverSeat.Changed:Connect(Controller.Drive())
    

    The problem is that you are not connecting the Drive function, you are connecting the result of the Drive function, and the returned result of Controller.Drive() is nil.

    So to fix your issue, remove the parentheses to pass the function to the connection.

    Controller.DriverSeat.Changed:Connect(Controller.Drive)