如何在 Lua 中使用中间 class 在 class 中调用 class 函数

How can I call a class function inside a class using middleclass in Lua

我一直在尝试弄清楚如何在 Lua 中的另一个 class 函数中调用 class 函数,但我认为可行的方法并不奏效。

local class = require 'libs.middleclass'

local Level = class('Level')

function Level:initialize(width, height, tileSize)
    self.width = width
    self.height = height
    self.tileSize = tileSize
    self.data = {}
    --Generate a 1D Array for the map data
    for x = 1, self.width do
        for y = 1, self.height do
            table.insert(self.data, 0)
        end
    end
end

function Level:get(x, y)
    return self.data[x + (y-1) * self.width]
end

function Level:set(x, y, type)
    self.data[x + (y - 1) * self.width] = type
end

function Level:draw()
    for x = 1, self.width do
        for y = 1, self.height do
            if self.Level:get(x, y) == 0 then
                love.graphics.setColor(255, 255, 255)
                love.graphics.rectangle("fill", x * tileSize, y * tileSize, tileSize, tileSize)
                love.graphics.setColor(0, 0, 0)
                love.graphics.rectangle("line", x * tileSize, y * tileSize, tileSize, tileSize)
            elseif self.Level:get(x, y) == 1 then
                love.graphics.setColor(255, 255, 255)
                love.graphics.rectangle("fill", x * tileSize, y * tileSize, tileSize, tileSize)
            end 
        end
    end
end

return Level

不确定您是否需要所有代码,但这是我的 level.lua 对象 class 中的代码。我认为使用 self.method 调用它会起作用,但它给了我:

objects/level.lua:29: attempt to index field 'Level' (a nil value)

这就是我能说的全部内容,因为我是在 Lua 中做 OOP 的新手,而且我正在使用 Love2D 框架,如果它有任何相关的话。

感谢您花时间回答。

所以 Egor 回答了问题,但在评论中这样做了。无论如何,我所要做的就是使用 self 而不是 self.Level。谢谢叶戈尔。