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
Before you make a thread asking for help, read this.
Post Reply
User avatar
Echo
Prole
Posts: 46
Joined: Fri Jul 13, 2012 4:50 pm
Location: Lucid Moon

How do I call Scripts in Love2d?

Post by Echo »

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...
User avatar
mickeyjm
Party member
Posts: 237
Joined: Thu Dec 29, 2011 11:41 am

Re: How do I call Scripts in Love2d?

Post by mickeyjm »

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...
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: How do I call Scripts in Love2d?

Post by ivan »

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
Your main file:

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
Your main file:

Code: Select all

require("myfile")
interface.foo()
These are just a couple of ways to avoid polluting the global namespace.
User avatar
Echo
Prole
Posts: 46
Joined: Fri Jul 13, 2012 4:50 pm
Location: Lucid Moon

Re: How do I call Scripts in Love2d?

Post by Echo »

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

Who is online

Users browsing this forum: Ahrefs [Bot] and 85 guests