Splitting up code

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Zeronix
Prole
Posts: 3
Joined: Mon Mar 13, 2017 6:05 am

Splitting up code

Post by Zeronix »

So I've been using Love for about a week, and I've been coding some simple games.

So far everything's been simple enough that I can keep everything in main.lua, but I'm guessing this won't work once I move on to bigger things and the code gets more complicated. Is it possible to store just the high-level architecture in my main.lua file and move all the low-level stuff to their own specialised modules? And if so how would I do that?

For context: I'm doing an extremely simple game where small boxes spawn every second in a random location and the goal is to click them as quickly as possible. The spawning works, but I want to add a score-keeper function and don't want to clog up my main.lua too much, so ideally I can code the score-keeper in a separate module.

Thanks in advance.
Attachments
main.lua
(777 Bytes) Downloaded 55 times
User avatar
yetneverdone
Party member
Posts: 446
Joined: Sat Sep 24, 2016 11:20 am
Contact:

Re: Splitting up code

Post by yetneverdone »

You could put other codes in another lua file. For example, put your scoring things in score.lua file, then use require to use it in your main.lua file

Code: Select all

--main.lua file
--require("path-to-lua")
require("score") --no need to put the .lua extension

function love.load()

end

--etc

User avatar
zorg
Party member
Posts: 3436
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Splitting up code

Post by zorg »

Anything's possible, and because of just that, it's hard to figure out on one's own how it should be implemented.
I'd personally recommend this guide by kikito.
That said, here's a small example on how i do things:

Code: Select all

-- a.lua
local a = {}
-- put stuff in a
return a

-- b.lua (could be main.lua too, doesn't matter)
local a = require('a')
-- now the a variable local to -this- file refers to the one defined in a.lua, meaning anything in that is accessible from here.
It's better to return a local table because this way there are no "hidden dependencies", you can clearly follow what you required and what's accessible where.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 54 guests