简体   繁体   中英

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

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
    }
}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM