Hexanix
Hexanix

Reputation: 77

Issue using "require()" in Lua, need help understanding why it won't work

I'm learning to use Lua, more specifically - the love2d libraries, and decided to try and organize my project by utilizing lua's 'require()' function. I know about package.path and the way it is used, but even after seemingly doing everything correctly, using a function from the external script returns 'true'. Here's the details:

-- Package.Path edit
package.path = package.path .. ';scripts/?.lua' 

-- Module requiring and inserting
-- Map module
mapModule = require('mapscript')

Continuing this further into the program, inside love.load():

 mapModule.map_generate(tilemap_1, MAP_PROPERTIES)

The map_generate() function in question shouldn't be returning anything, it is simply a bunch of loops to create a square matrix of values, which takes two arguments. I don't think it is as important, so to keep this post tidier I am linking a pastebin: https://pastebin.com/ZaE7Tzpa

The file tree is the following:

`-main.lua
 -conf.lua
 -run.bat (to quickly be able to run the main.lua)
 -scripts 
   -- mapscript.lua
 -assets

`

When running the file I recieve the following error:

main.lua: 51: attempt to index global 'mapModule' (a boolean value)

HOWEVER when using map_generate() directly instead, the issue disappears.

If I understand correctly, the error means that the require() has failed to load the script. Why does this happen? Why does using the function directly work instead? What's the point of the local variable you bind the require to?

Upvotes: 3

Views: 3883

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473182

Lua modules should not declare functions in the global table. The way they're supposed to work is by putting functions in a table, which they then return. This allows the code fetching the module to decide how that module's functions will be accessed.

So your mapscript.lua file should put its functions in a table. Something like this:

local mod = {}

function mod.map_generate() ... end

return mod

Upvotes: 4

Related Questions