attempt to index local 'def' (a nil value)

杀马特。学长 韩版系。学妹 提交于 2021-02-10 19:59:25

问题


I'm working on a game. At a certain point, I would like to create special GameObject. The special GameObject is called Projectile and is the same as GameObject but has a dx and dy as well as some other functions that only a projectile will have. I am trying to make Projectile extend the GameObject class, but I run into issues when I try to create an instance of Projectile. I've tried different ways of declaring Projectile and shuffling declaration order but can't seem to figure out why I'm getting the error mentioned in the title. Thank you!

The following works just fine:

table.insert(self.dungeon.currentRoom.objects, GameObject(
                        GAME_OBJECT_DEFS['pot'],
                        self.player.x,
                        self.player.y
                    ))

But when I change "GameObject" to "Projectile" it does not.

table.insert(self.dungeon.currentRoom.objects, Projectile(
                        GAME_OBJECT_DEFS['pot'],
                        self.player.x,
                        self.player.y
                    ))

The rest is supporting code. I'm using Class code from Matthias Richter

require 'src/Projectile'
require 'src/GameObject'
require 'src/game_objects'

GameObject = Class{}

function GameObject:init(def, x, y)
    -- string identifying this object type
    self.type = def.type

    self.texture = def.texture
    self.frame = def.frame or 1

    -- whether it acts as an obstacle or not
    self.solid = def.solid

    self.defaultState = def.defaultState
    self.state = self.defaultState
    self.states = def.states

    -- dimensions
    self.x = x
    self.y = y
    self.width = def.width
    self.height = def.height

    -- default empty collision callback
    self.onCollide = def.onCollide
end

Projectile = Class{__includes = GameObject}

function Projectile:init()
    GameObject.init(self, def)

    self.dx = 0
    self.dy = 0
end

GAME_OBJECT_DEFS = {
    ['pot'] = {
        type = 'pot',
        texture = 'tiles',
        frame = 14,
        width = 16,
        height = 16,
        solid = true,
        defaultState = 'idle',
        states = {
            ['idle'] = {
                frame = 14,
            }
        },
        onCollide = function()
        end
    }
}

回答1:


function Projectile:init()
    GameObject.init(self, def)

    self.dx = 0
    self.dy = 0
end

def is nil

so in

function GameObject:init(def, x, y)
    -- string identifying this object type
    self.type = def.type

you index a nil value.

Same will happen for x and y



来源:https://stackoverflow.com/questions/61495184/attempt-to-index-local-def-a-nil-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!