1
votes

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.

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. I thought that calling it using self.method would work, but it gives me:

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.

Thanks for taking your time to answer.

1
Simply write self:get(x, y) instead of self.Level:get(x, y) - Egor Skriptunoff
It worked now I feel stupid, thanks. - MeArio

1 Answers

0
votes

So Egor answered the question, but did so in the comments. Anyway all I had to do was use self instead of self.Level. Thanks Egor.