Invalid argument #1 to 'pairs' (table expected, got nil)

Hello Fellow Developers.

I’m working on a boat suspension script and I’ve ran across an error that I have never seen. Currently I am at a state where I’m completely confused on what to do, or what is causing this error to happen.

Module:

local Module = {}
Module.__index = Module
-- Services / Constants --
local RunService = game:GetService('RunService')
local _Boat = require(script.Parent)
----

-- Functions --
function Module.new(Model:Model)
	local self = setmetatable({},Module)
	self.Model = Model
	self.Motors = {}
	-- Function --
	self:GetOperators()
	---
	self.Model.PrimaryPart:SetNetworkOwner(nil)
	RunService.Heartbeat:Connect(function()
		self:Update()
	end)
	---
	return self
end
---
function Module:GetOperators()
	-- For Statement --
	for _,Operator in pairs(self.Model.Operators:GetChildren()) do
		table.insert(self.Motors,_Boat.new(self.Model,Operator))
	end
end
---
function Module:UpdateOperators()
	-- For Statement --
	for _,Operator in pairs(self.Motors) do
		Operator:Update()
	end
end
---
function Module:Update()
	self:UpdateOperators()
end
----
return Module

Problematic Function:

function Module:UpdateOperators()
	-- For Statement --
	for _,Operator in pairs(self.Motors) do
		Operator:Update()
	end
end

Problematic Line:

for _,Operator in pairs(self.Motors) do

It’s because self.Motors doesn’t exist. Could you show where you call this function in your code?

1 Like

I use a server script to call the function.

-- Services --
local ReplicatedStorage = game:GetService('ReplicatedStorage')
-- Constants --
local GameModules = ReplicatedStorage:FindFirstChild('GameModules')
local _Motor = require(GameModules:FindFirstChild('_Boat'):FindFirstChild('_Motor'))
----

-- Use Functions --
_Motor.new(script.Parent)
_Motor:UpdateOperators()
----

Okay, the problem is that you’re referencing the module, not the class you just created.

Fixed code:

-- Services --
local ReplicatedStorage = game:GetService('ReplicatedStorage')
-- Constants --
local GameModules = ReplicatedStorage:FindFirstChild('GameModules')
local _Motor = require(GameModules:FindFirstChild('_Boat'):FindFirstChild('_Motor'))
----

-- Use Functions --
local newMotor = _Motor.new(script.Parent)
newMotor:UpdateOperators()
----
1 Like

If I use either :Update() or :UpdateOperators() I would get the same error

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.