How to Create a Lua Module



Lua programming language, logo


A module in the Lua programming language is a piece of code that contains functions and variables: it’s an user library. It’s a powerful way to split your code in several files. A module is loaded using the Lua require keyword. The module is coded in a file with the .lua extension and this file must be present in Lua package search path (package.path).

A module is actually a Lua table (see HERE for a quick introduction to Lua) with functions. The table is returned at the end of the module file. Here is an example of a simple Lua module in a file called DemoLib.lua:

File module: DemoLib.lua

local demo_mod = {} -- The main table

function demo_mod.Mult(a, b)
  return a * b
end

return demo_mod



Now in the main Lua code, we can load the module and start using it with the following code:

-- Update the search path
local module_folder = "/home/jegx/my_kool_mods/"
package.path = module_folder .. "?.lua;" .. package.path

-- Load the module
demo = require "DemoLib"

-- Use it!
local result = demo.Mult(10, 2)



If the module does not reside in the package search path, you can update the package.path with the path to the folder where is stored the module file.

If for some reasons you need to reload the module (live coding for example), just nil the package.loaded["DemoLib"]:

...
package.loaded["DemoLib"] = nil
demo = require "DemoLib"
...



I started to use Lua modules in latest code samples of GLSL Hacker in order to create a high level and simpler interface for the demos. The first use of Lua modules can be found in the demo of this article.



References:

  • Programming in Lua, 2nd edition, chapter 15








[ Subscribe to Geeks3D latest news by email ]

Geeks3D.com

↑ Grab this Headline Animator