Page 1 of 1

How do I call Scripts in Love2d?

Posted: Thu Jul 26, 2012 10:05 am
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...

Re: How do I call Scripts in Love2d?

Posted: Thu Jul 26, 2012 10:15 am
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.

Re: How do I call Scripts in Love2d?

Posted: Thu Jul 26, 2012 10:21 am
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.

Re: How do I call Scripts in Love2d?

Posted: Thu Jul 26, 2012 2:09 pm
by Echo
thanks for the awesome help. It was much easier that I thought.
(^-^)(^_^)(^0^)