[Solved] Splitting a LUA file into smaller pieces

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
User avatar
shatterblast
Party member
Posts: 136
Joined: Tue Dec 11, 2012 9:47 pm
Location: Dallas, Texas, USA

[Solved] Splitting a LUA file into smaller pieces

Post by shatterblast »

I want to split my "main.lua" file into smaller bits, one for each HUMP gamestate. "Require" loads a library, but unless I'm wrong, it doesn't append to a LUA file so that it could act in unison like a bigger file. How can I split a file into smaller pieces? Thank you.
Last edited by shatterblast on Fri Dec 05, 2014 5:18 am, edited 1 time in total.
User avatar
Kingdaro
Party member
Posts: 395
Joined: Sun Jul 18, 2010 3:08 am

Re: Splitting a LUA file into smaller pieces

Post by Kingdaro »

Well, it doesn't need to "act in unison", you're over thinking this.

The require function treats separate files as function, as in, defining a function in code and calling it is the same as creating a file and requiring it. All require does is "call" the file, and return whatever result the file gives at the end. There are some other extra bits the require function does, but for now, this is all you need to know.

For example, if you had a gamestate for the menu and for the game, you could organize your files like this:

Code: Select all

-- game.lua
local Game = {}

-- Game gamestate functions

return Game

Code: Select all

-- menu.lua
local Menu = {}

-- Menu gamestate functions

return Menu

Code: Select all

-- main.lua
gamestate = require 'hump.gamestate'

Menu = require 'menu'
Game = require 'game'

function love.load()
   gamestate.switch(Menu)
end
User avatar
shatterblast
Party member
Posts: 136
Joined: Tue Dec 11, 2012 9:47 pm
Location: Dallas, Texas, USA

Re: [Solved] Splitting a LUA file into smaller pieces

Post by shatterblast »

Beautiful! It works just like you put it. Many thanks.
Post Reply

Who is online

Users browsing this forum: Amazon [Bot], Google [Bot] and 9 guests