How to Use Lua require() in GeeXLab Demos

GeeXLab - Lua package lib

Lua’s require() function is like dofile(): it allows to load libraries. But there are some important differences:
require uses a search path to find libraries
require does caching

require uses the package.path to search for a library. package.path contains all possible folders with Lua libraries. But before loading a library, Lua looks into the package.loaded table to see if the library is already loaded: it’s the caching.

Let’s see an example. We want to load imgui.lua lib (stored in {GeeXLab folder}/libs/lua/). The quick way to load this Lua file is:

local lib_dir = gh_utils.get_lib_dir()
dofile(lib_dir .. "lua/imgui.lua")

Now the same thing but using require:

local lib_dir = gh_utils.get_lib_dir() 		
package.path = package.path .. ";" .. lib_dir .. "lua/?.lua;"
require "imgui"

require looks into package.path and replace all ? by imgui.

imgui.lua is a Lua file that contains some global variables and functions. Now, if we want to load the following lib (mymodule.lua) stored in the demo folder (at the same level than init.lua or frame.lua):

local mymodule = {}
    print("Hello World!")
function mymodule.hello()
  return "Hello from mymodule!"
return mymodule

The code to load this lib would be:

local demo_dir = gh_utils.get_demo_dir() 		
package.path = package.path .. ";" .. demo_dir .. "./?.lua;"
mymodule = require "mymodule"

Remark: Lua needs a proper package.path. Each path in package.path folder must have the same convention about folder separators: either use “/” (Linux and Windows) or “\\” (Windows).
For example:

package.path = package.path .. ";C:\\temp/lua/?lua;"

won’t be appreciated by Lua.

You have to fix it with

package.path = package.path .. ";C:\\temp\\lua\\?lua;"


package.path = package.path .. ";C:/temp/lua/?lua;"

The demo:
GeeXLab - Lua package lib

The demo is available in the OpenGL 2.1 demopack here: geexlab-demopack-gl-21/d46-lua-package-require/main.xml


Leave a Comment

Your email address will not be published. Required fields are marked *