Search code examples
lualove2d

Love2d: Creating multiple of the same object from a different file


I was wondering if it is possible to create multiple of the same object that is written in a separate file. I have two files: main.lua and player.lua. This is player.lua:

    local player = { }
function player:create (x, y, sp)
    self.img = love.graphics.newImage ('images/player.png')
    self.x = x
    self.y = y
    self.speed = sp
end

return player

I want to include this file in main.lua. I know I can't use require "player" because require only allows a file to be loaded once but it doesn't need me to specify a file path. I tried using dofile() which actually did exactly what I wanted it to do, however, it does requires me to specify a full file path which I don't want to do. So this is the part from main.lua:

local Player = require "player"
local Player2 = require "player"
-- local Player = dofile("/long/path/to/game/player.lua")

If I can't use require, is there a way to get the current file directory and use it like this:

local Player = dofile(filepath .. "player.lua")

Solution

  • You should approach this by changing create to a function which actually creates new instances of Player, instead of modifying the singleton object.

    -- Player.lua
    local Player = {}
    
    function Player:create (x, y, sp)
        self.__index = self
    
        return setmetatable({
            img = love.graphics.newImage('images/player.png'),
            x = x,
            y = y,
            speed = sp
        }, self)
    end
    
    return Player
    

    Now you can use Player:create to create multiple instances.

    -- main.lua
    local Player = require 'Player'
    
    local player1 = Player:create(10, 10, 5)
    local player2 = Player:create(40, 40, 2)
    

    Consider reading chapter 16 of Programming in Lua, which covers Object-Oriented Programming.