Loading level data from separate file

This might come across as a dumb question, but I have been beating my head against the wall for the past hour trying to figure this out to no avail.

I have created a separate file (LevelData.lua) that exists in the same directory as the code that runs the main logic of the game. Roughly speaking, LevelData is structured like this:

local levelData = {}

-- Define levels as a table
levelData.levels = {
...
}

-- Active level (initially nil)
levelData.activeLevel = nil

-- Method to set the active level
function levelData:setActiveLevel(levelIndex)
    self.activeLevel = self.levels[levelIndex]
end

-- Method to get the active level
function levelData:getActiveLevel()
    return self.activeLevel
end

return levelData

Now, in my game logic function, I am trying to import and interract with the data like this:

import "LevelData"

print(LevelData.levels[1])

However, when I do this, I run into an error, "Attempt to index a nil value (global 'LevelData').

I have triple checked that my filenames and folder structure is correct. LevelData.lua should be returning at the end of the function, but something is going wrong.

I think you should do

Leveldata = levelData

At the end of your file instead of the

return levelData

you have there

That cleared up the issue! I am still a bit confused about how the data is structured. Since 'LevelData' is not being initialized as a local variable, is it instead being initialized when the lua file is referenced? Sorry that sounds confusing, but I am not familiar with the the idea of a function/file referencing a variable that is itself.

imports are just file concatenation. Hence, you don't need a return. The docs say:

The Playdate runtime uses import instead of the standard Lua require function, and it behaves a little differently: All files imported from main.lua (and imported from files imported from main.lua, and so on) are compiled into a single pdz file, and import runs the code from the file only once.