Re: How to use modules?
Posted: Thu May 12, 2022 12:45 am
Yes it works, but.
If you keep doing things global, that will end up biting you in the butt sooner than later.
Whatever the module (in this case Audio.lua) returns, is what the function require() returns in turn. That will help you make things local and looking nice.
This works without adding 'a' to the global scope:
Audio.lua:
main.lua:
You can also require the same file from other locations. The nice thing about require() is that it doesn't load the file multiple times; instead it caches the return value and returns it immediately if the file was loaded previously. Therefore, using require() only has a performance penalty the first time it's executed; other modules don't need to worry about that.
If you keep doing things global, that will end up biting you in the butt sooner than later.
Whatever the module (in this case Audio.lua) returns, is what the function require() returns in turn. That will help you make things local and looking nice.
This works without adding 'a' to the global scope:
Audio.lua:
Code: Select all
local a = {} -- now a is a local table
--Audio
-- add functions to the local table a
function a.load()
source = love.audio.newSource( "Backgroundsong.wav", "stream" )
end
function a.update(dt)
if not source:isPlaying( ) then
love.audio.play( source )
end
end
return a -- return the value of the local, that is, the table
Code: Select all
--main
local a = require("Audio") -- the returned value is what the Audio module returned, and we're setting the local variable 'a' to that
function love.load()
a.load()
end
function love.update(dt)
a.update(dt)
end