lua 错误:尝试索引字段 'frames'(一个空值)(但自身和 lacal 错误)

我很困扰地理解 self 和 local 的值。 这是我的 asteroid.lua。我在 :create 内部创建了本地陨石,尝试在其他函数中使用它,但它没有正确工作。

-- 类声明

Asteroid = {}
Asteroid.__index = Asteroid

function Asteroid:create()
local asteroid = {}
setmetatable(asteroid, Asteroid)

-- 动画数据
asteroid.frames = {}
asteroid.currentFrame = 1
asteroid.frameDuration = 0.04  -- 0.016
asteroid.frameTimeRemaining = asteroid.frameDuration
asteroid.x = 0
asteroid.y = 0

return asteroid
end

function Asteroid:init()

-- 使用循环加载一堆文件!
for index= 0, 15 do
    -- 使用逻辑构建文件名...
    file = 'art/large/a100'

    -- 考虑到额外的 0
    if index < 10 then
        file = file .. '0'
    end

    -- 添加文件号,然后 .png
    file = file .. tostring(index) .. '.png'

    -- 加载文件...(我们将使用 lua 的第一个索引来友好地对待)
    self.frames[index + 1] = love.graphics.newImage(file)

    if self.frames[index + 1] ~= nil then
        print('载入帧 ' .. tostring(index + 1))
    end
end

-- 随机设置速度!
self.velocity = {}
self.velocity.x = math.random(-76.0, 76.0)
self.velocity.y = math.random(-76.0, 76.0)

end

Asteroid.updateAnimation = function(deltaTime)
-- 将变量捕获到“易于输入”的变量中
local ftr = Asteroid.frameTimeRemaining

这部分(local ftr)是我的问题:尝试索引一个空值。 我尝试了不同的方式,如 self.frameTimeRemaing,但我无法弄清楚。 有人知道我如何修复这个本地吗?

-- 减去时间
ftr = ftr - deltaTime

-- 如果帧已经结束...
if ftr < 0 then
    Asteroid.nextFrame()
    Asteroid.frameTimeRemaining = Asteroid.frameDuration
else
    Asteroid.frameTimeRemaining = ftr
end
点赞
用户107090
用户107090

不看代码的其余部分,我只能猜测。尝试这个:

function Asteroid:updateAnimation(deltaTime)
-- 在此函数中使用 self,而不是使用 Asteroid
end
2017-11-01 00:58:25