2

I've been working with Love2d recently to build a Conway's Game of Life implementation.

I really like the framework, but I haven't been able to figure out how to modularize my code, which I feel is crucial to solid code structure.

What I'm wanting to do is be able to import a file that has different functions in it and be able to access that through my main lua file. I have been able to write scripts and run entire files, but not specific functions.

Is there a way to do this in Lua? If so, how?

Thanks!

Benjamin Kovach
  • 3,190
  • 1
  • 24
  • 38

2 Answers2

4

You can use the require function in LÖVE. It works similarly to how it works in Lua.

-- lib.lua

local lib = {} -- table to store the functions

function lib.inc(x)
  return x + 1
end

return lib

And here is how you require it in another file (for example, main.lua) and use it:

local lib = require('lib')

function love.load()
  print(lib.inc(1)) -- prints '2' in the terminal
end
kikito
  • 51,734
  • 32
  • 149
  • 189
-1

Lua supports modules. Here is a tutorial on using them http://lua-users.org/wiki/ModulesTutorial

piokuc
  • 25,594
  • 11
  • 72
  • 102
  • 1
    Modules aren't really needed for what Benjamin is asking. Besides, the module function has several known flaws - http://lua-users.org/wiki/LuaModuleFunctionCritiqued and I think it has been deprecated in Lua 5.2 – kikito Mar 12 '12 at 21:46