I’m trying to use OOP to create a grid system. Currently, there’s a problem with remembering a set of tiles that I don’t fully understand.
local Grid = {}
Grid.__index = Grid
function Grid.new(size)
local self = setmetatable({}, Grid)
self.Size = size
self.Tiles = {}
return self
end
function Grid:AddTile(object, position)
local tile = Tile.new() -- an object with properties: Object, Position
tile.Object = object
tile.Position = position
table.insert(self.Tiles, tile)
end
function Grid:GetTile(pos)
local t
for _, tile in pairs(self.Tiles) do
if tile.Position == pos then
t = tile
break
end
end
return t
end
My problem is that when I use AddTile, the Tiles are added only during that scope (ot whatever you call it). If I try to reference self.Tiles
anywhere else (like GetTile), it outputs nil
.
The specific error that pops up when I use GetTile is:
ServerScriptService.Grid:42: invalid
argument #1 to 'ipairs' (table expected, got nil)
Any help here would be appreciated.
(I’m going to sleep after I post this. I won’t be answering anything until a few hours later.)