为什么 'self' 在我的 Love2D Lua 代码中返回错误?

Why is 'self' returning an error in my Love2D Lua code?

我对 Lua 和 Love2D 还很陌生,只是在修改我在在线教程中找到的一些代码。但我不断遇到错误:Map.lua:32: attempt to index local 'self' (a number value).

这是我的 main.lua 代码:

require 'Map'

local speed = 1000
local score = 0

map = Map:create()

function love.load()
sprite = love.graphics.newImage("Game Boy Advance - LEGO Island 2 The Bricksters Revenge - Pepper.png")
x = love.graphics.getWidth() / 2
y = love.graphics.getHeight() / 2
end

function love.update(dt)
score = score + 1
success = "no"
end

function love.keypressed(key)
    success = "yes"
    if key == "right" then
        x = x + speed
    end
    if key == "left" then
        x = x - speed
    end
    if key == "escape" then
        love.event.quit()
    end
end

function love.draw()
--love.graphics.clear(108,140,0,255)
--love.graphics.draw(sprite, x, y)
map = Map:create() -- returning nil
--love.graphics.print(map[2])

map:render()
end

和 Map.lua 代码:

require 'Util'

Map = {}
Map.__index = Map

TILE_FLOOR = 1
TILE_EMPTY = 12

function Map:create()
    local this = {
        spritesheet = love.graphics.newImage("Amiga Amiga CD32 - Jail Break - Blocks & Backgrounds.png"),
        mapHeight = 30,
        mapWidth = 28,
        tileheight = 12,
        tilewidth = 12,
        tiles = {}
    }

    this.tileSprites = generateQuads(this.spritesheet, 12, 12)

    setmetatable(this, self)

    for y = 1, this.mapHeight do
        for x = 1, this.mapWidth do
            this:setTile(x, y, TILE_FLOOR)
        end
    end
    return this
end

function Map:getTile(x, y)
    return self.tiles[(y - 1) * self.mapWidth + x]
end

function Map:setTile(x, y, tile)
    self.tiles[(y - 1) * self.mapWidth + x] = tile
end

function Map:render()
    for y = 1, self.mapHeight do
        for x = 1, self.mapWidth do
            love.graphics.draw(self.spritesheet, self.tileSprites[self.getTile(x,y)], (x-1) * self.tilewidth, (y-1) * self.tileheight)
        end
    end
end

和 Util.lua 代码:




function generateQuads(sheet, tilewidth, tileheight)
    local sheetheight = sheet:getHeight() / tileheight
    local sheetwidth = sheet:getWidth() / tilewidth

    local counter  = 1
    local quads = {}

    for y = 0, sheetheight - 1 do
        for x = 0, sheetwidth - 1 do 
            quads[counter] = love.graphics.newQuad(x * tilewidth, y  * tileheight, tilewidth, tileheight, sheet:getDimensions())
            counter = counter + 1
        end
    end

    return quads
end

这里完全是初学者 - 问题可能很简单,但我很难过:( 谢谢,祝你有美好的一天! :)

Map:render 中,您错误地调用了方法 Map:getTile,它需要 self 作为第一个参数,仅使用一个点,因此将 x 作为 [=14] =]、y 作为 xnil 作为 y:

love.graphics.draw(self.spritesheet, self.tileSprites[self.getTile(x,y)], (x-1) * self.tilewidth, (y-1) * self.tileheight)`

参见 difference between . and :

触发错误。您必须使用冒号 (:) 调用方法 self:getTile 以将 self 作为第一个参数传递:self:getTile(x, y):

love.graphics.draw(self.spritesheet, self.tileSprites[self:getTile(x,y)], (x-1) * self.tilewidth, (y-1) * self.tileheight)`