Can anyone explain this? It’s pretty late in the day for my brain but this is not computing:
EDIT: I’ve simplified this question
.
module1.lua
local M = {}
M.var = 'Hello'
return M
.
How come this fails:
main.script
local n = 1
local module_a = require('module'..n)
print(module_a.var)
Console output
ERROR:SCRIPT: /main/main.script:7: module 'module1' not found:
no file 'module1'
stack traceback:
[C]: in function 'require'
/main/main.script:7: in function </main/main.script:1>
.
When this works:
main.script
local n = 1
local module_a = require('module'..n)
local module_b = require('module1')
print(module_a.var)
print(module_b.var)
Hi @approbo.games!
I think this has been answered before, but the short story is that when building/bundling the project we scan all scripts (in use) for requires to determine exactly what modules need to be included. This requires (ha!) the required module name to be a string constant so we can parse it simply and safely. We can’t execute the code to determine the dependencies.
Also, I think the safest bet is to put your requires at the top of your file before anything else. IIRC we don’t really use the full lua grammar, just some magic regexps.
While we’re on the topic, is there anything I should watch out for when using require?
I’m asking because I’ve put my general-purpose functions and variable declarations (mostly presets) into separate .lua files so my main script isn’t cluttered by them. Could I run into trouble because of that, or is that fine?
Make sure you get the capitalization (lowercase/uppercase) right in the require paths, and make sure it’s consistent between all requires of that module in your project
Lua modules in general don’t play that well with our hot reload feature. If you want to tweak “constants” while running your game using hot reload, it’s generally easier to put them in scripts. There are ways to partially work around this by creating an on_reload in your scripts and haxing package.loaded - also described in the reference.