简体   繁体   English

如何在Lua中使用middleclass调用类中的类函数

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

I've been trying to figure out how to call a class function inside another class function in Lua, but the way I thought would work doesn't. 我一直在试图弄清楚如何在Lua中的另一个类函数中调用类函数,但我认为的方式不会。

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

Not sure if you need all of the code, but this is what I have in my level.lua object class thingy. 不确定你是否需要所有的代码,但这是我在level.lua对象类中的东西。 I thought that calling it using self.method would work, but it gives me: 我认为用self.method调用它会起作用,但它给了我:

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

That's about all I can say about it since I'm new to doing OOP in Lua, also I'm using the Love2D framework if that is in any way relevant. 这就是我可以说的全部内容,因为我刚开始在Lua做OOP,我也在使用Love2D框架,如果这有任何相关的话。

Thanks for taking your time to answer. 感谢您抽出宝贵时间回答。

So Egor answered the question, but did so in the comments. 所以Egor回答了这个问题,但在评论中这样做了。 Anyway all I had to do was use self instead of self.Level. 无论如何,我所要做的就是使用self而不是self.Level。 Thanks Egor. 谢谢叶戈尔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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