## How do I call Scripts in Love2d?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Echo
Prole
Posts: 46
Joined: Fri Jul 13, 2012 4:50 pm
Location: Lucid Moon

### How do I call Scripts in Love2d?

how can I call a script in Love2d?
I want to have function love.draw in another script instead of shoving everything in main.lua.
or is this just impossible...

mickeyjm
Party member
Posts: 237
Joined: Thu Dec 29, 2011 11:41 am

### Re: How do I call Scripts in Love2d?

You can do it like this:

Put this at the top of main.lua (Where OTHERFILE is the name of your "script"):

Code: Select all

require "OTHERFILE" --Note the lack of ".lua"
and then it will run when main.lua is run.
Your screen is very zoomed in...

ivan
Party member
Posts: 1546
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

### Re: How do I call Scripts in Love2d?

You can compile Lua script files at runtime using:

Code: Select all

require("filename")
Notice that you don't write the extension of the file, so:

Code: Select all

require("myfile.lua")
Should be:

Code: Select all

require("myfile")
If your file is not in the root folder (or one of the default folders searched by require) then its:

Code: Select all

require("directoryname.filename")
Where you use the "." symbol to indicate a directory (instead of the typical "/" or "\\").
There's also "dofile" but I heard it's unsupported in Love2D.

Make sure your functions in the required file are global.
Otherwise they won't be accessible from your main file.

If your functions in the included file are NOT global, you can have several options.
You can return a "table" containing the functions from the included file or use the "module" keyword:
myfile.lua

Code: Select all

local function foo() end
local function bar() end
local interface = { foo = foo, bar = bar }
return interface

Code: Select all

interface = require("myfile")
interface.foo()
The module keyword:
myfile.lua

Code: Select all

module ("interface")
-- the following function are NOT global
function foo() end
function bar() end

Code: Select all

require("myfile")
interface.foo()
These are just a couple of ways to avoid polluting the global namespace.

Echo
Prole
Posts: 46
Joined: Fri Jul 13, 2012 4:50 pm
Location: Lucid Moon

### Re: How do I call Scripts in Love2d?

thanks for the awesome help. It was much easier that I thought.
(^-^)(^_^)(^0^)

### Who is online

Users browsing this forum: Google [Bot] and 4 guests