[英]bad argument #1 to 'insert' (table expected, got nil) error in love2d lua
i keep receiving an error when i try to run my lua script.当我尝试运行我的 lua 脚本时,我不断收到错误消息。 The error is: bad argument #1 to 'insert' (table expected, got nil)
错误是:错误的参数 #1 到“插入”(表预期,得到零)
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
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)
.根据您显示的代码,您的
gameLoop
表不包含clocks
成员,因此您实际上是将nil
传递给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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.