0
votes

i keep receiving an error when i try to run my lua script. The error is: bad argument #1 to 'insert' (table expected, got nil)

here is my gameloop code:

local GameLoop = {}

local insert = table.insert
local remove = table.remove

function GameLoop:create()

    local gameLoop = {}

    function gameLoop:addLoop(obj)

        insert(self.clocks,obj)

    end

    function gameLoop:update(dt)

        for clocks = 0,#self.clocks do
            local obj = self.clocks[clocks]
            if obj ~= nil then
                obj:tick(dt)
            end
        end

    end

return gameLoop

end

return GameLoop
1

1 Answers

0
votes

From the code you've shown, your gameLoop tables do not contain a clocks member, so really you are passing nil to the first argument of insert(self.clocks, obj).

Simple fix is to add that member.

local gameLoop = { clocks = {} }

As an aside, it's usually better to write this type of construct using metatables, since it reduces function duplication.

local insert, remove =
    table.insert, table.remove

local GameLoop = {}
GameLoop.__index = GameLoop

function GameLoop:create ()
    return setmetatable({
        clocks = {}
    }, self)
end

function GameLoop:addLoop (obj)
    insert(self.clocks, obj)
end

function GameLoop:update (dt)
    for _, clock in ipairs(self.clocks) do
        obj:tick(dt)
    end
end

return GameLoop