3

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?

4
  • Your mapscript module must return the table mapModule Commented Sep 16, 2018 at 20:33
  • What are you returning from mapscript.lua? Commented Sep 16, 2018 at 20:35
  • @luther the file returns nothing, it only has the one function in it. Commented Sep 17, 2018 at 9:52
  • So essentially the fact I'm assigning the value of require (which as I am not returning anything is nil) to MapValue makes it useless, I think I see the obvious flaw, silly me. Thanks a bunch Commented Sep 17, 2018 at 9:53

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.