Including a lua module (SOLVED)

I have a lua module “data.lua” and am ‘requiring’ is from a script file in the same directory using:

local data = require (“data”)

When building I get the error

the module ‘/data.lua’ can’t be found

I’ve checked and double-checked but can’t see the problem… can anyone help?

Last silly question for today, promise :grin:

2 Likes

You need to specify the full path from the root of the project and use ‘.’ as a path separator. So, if you have data.lua in my/path you would require it like this:

local data = require("my.path.data)
3 Likes

That works - brilliant, thanks!

1 Like

I am having this same problem. I am trying to call a module called camera.lua in a separate camera.script. I am getting the “This module cannot be found” error message. I tried your suggestion in completely writing out the full path using this

local camera = require (“lets go.content.main.modules.camera”)

my project is called "lets go"
the module is in a folder called “modules” within the “main” folder. Do you have any suggestions on where I should go from here? Thank you.

You should specify the path from the root of the project, ie from where your game.project file is. Judging from what you’ve written it seems like you shouldn’t include “lets go” (btw, I don’t believe a require directive can contain any white space).

Given the following folder structure:

project_root/
+---main/
|   +---modules/
|       +---camera.lua
+---game.project

local camera = require ("main.modules.camera")

Adding to @britzl answer - variant

local camera = require (“main/modules/camera”) - work too

I’m not sure that will work on windows though. ‘.’ will be replaced with the current system path separator. (Correct me if I am wrong here!)

It work on windows too.

You should use the dot ‘.’ for guaranteed cross platform compatibility. package.loaders mentions:

with each dot replaced by a “directory separator” (such as “/” in Unix)

Note that Defold replaces the default loaders with a single loader that only searches within the game package itself.