Search code examples
filelua2d-gameslove2d

Lua, Love2d, two games with the same class name in different folders


I'm new to Lua and Love2D, I did 2-3 simple games and I wanted to put them together. I did a window where you choose which game you want to play. It succeed; with a little problem. Two of my games use a ball. So both have a Ball.lua File. I use the require function to load the Ball file in each of my games. It works at first, I can play Game1, go back and play Game2 without any problem. But if I go back and want to play the Game1 again. His ball.lua File will not be required since require only load once. Then there will have an error since my game1 is trying to use my Game2's ball Class.

I wanted to know which solution would be best :

  1. Just rename the files. (I would like to avoid it, feels hardcoding to me)
  2. Use doFile. (I never used it, I don't even know if it would work)
  3. Require the two Ball's Classes in my Main menu and pass it by parameter when loading each game (Don't know if it would work too)

If you want to see my code for more explanation, here's the link : https://github.com/cbelangerstpierre/Games/tree/main/Games

Thanks in advance !


Solution

  • As you know, require will only execute each file once. However it will also save the return value of the file so you can require the file as many times as you want and still get the same value.

    In your Ball.lua files, make your Ball declarations local:

    local Ball = Class{}
    

    Then at the bottom of those files add:

    return Ball
    

    Then, change your main.lua files to store to the global Ball variable:

    Ball = require "Atari-Breakout.Ball"
    

    and

    Ball = require("Switching-Ball.Ball")
    

    Ideally, it's recommended to make all of your variables local and return tables from the files that you need to require.