First of all, Lua libraries can be written either in pure Lua, or in C (or C++ or any other language, but interfacing with Lua via the C API). Or mixing the two approaches. I'll try to explain the pure Lua approach only, the latter being a bit more involving (but easier to understand once the pure Lua approach is clear).
A Lua library, or 'module', is essentially a Lua script that is executed by other scripts using
require( ) and that returns a table containing functions, variables, and whatever else the module developer wants to 'export' to its user. Note however that the script need not actually return a table. It is just required to return a 'truthy' value (i.e. anything but nil or false), but the common practice is to return a table which we'll call the 'module table', and put there all the stuff to be exported.
Let's see a simple working example. A module that exports a few trivial functions and variables:
Lua:
-- File: mylib.lua - a simple module
local M = { } -- this is the module table we'll return
-- A few functions to export:
M.foo = function(x)
print("foo", x)
end
M.bar = function(x, y)
print("bar", x, y)
end
M.baz = function(x, y, x)
print("baz", x, y, z)
end
-- You may also add some variables:
M._VERSION = "mylib 0.1"
M._AUTHOR = "myself"
M.pi = 3.14
return M -- this is the value that will be returned when executing require("mylib")
To be usable from other scripts, the "mylib.lua" script must be installed (i.e. copied, or moved) to one of the directories where
require( ) looks for modules. See the manual for details.
Finally, a user script could then load and use the module like this:
Lua:
-- A user of the mylib.lua module
local mylib = require("mylib")
-- on success, the mylib variable now contains a reference to the table M
-- (note that you need not call the variable 'mylib', you may call it whatever you want)
-- print the version info:
print("Loaded "...mylib._VERSION)
-- execute functions from the module:
mylib.foo(123)
mylib.bar("Egan Bernal", "won the Giro!")
mylib.baz(1, 2, 3)