Using Lua loadfile(...) from system.ResourceDirectory on Android

Hi,
For a first game I had created descriptions of “levels” as .lua files ; in order to dynamically access the list of levels and avoid errors, I replaced “require” with a loadfile call:

local function loadLevel(level_index)
local path = system.pathForFile( "level/" .. level_index.. ".lua", system.ResourceDirectory );
local file = loadfile(path);
return file and file(); -- result of execution if exists
end

This works in the Simulator, but fails both on Android and HTML builds; documentation describes a related Android limitation in https://docs.coronalabs.com/api/library/system/ResourceDirectory.html , but I’m not sure what is the right workaround.

Will the above code work if I just change the extension of my data files to something else than .lua ? Or should I use a different file format (e.g. .json, but it would be more limited) ?
Or what is the proper way to support a collection of level configurations for my game that can be independently edited?

I appreciate your help and advice on how to best work around this problem…
-ivec

Use io.open() as described in the Lua docs https://www.lua.org/manual/5.1/manual.html#5.7

It won’t load a Lua file into the runtime environment for usage, but it will let you open and save data (including levels).

A convenient Solar 2d doc describing the usage of the native IO functions as it pertains to saving and loading Lua tables in JSON format is here: https://docs.coronalabs.com/tutorial/data/jsonSaveLoad/index.html

Thank you for your response.
Knowing which way to go it was easy to correct my function:

local function loadLevel( level_index)
local path = system.pathForFile( “level/”…level_index…".json", system.ResourceDirectory )
local file = io.open(path,“r”)
if not file then return end
local contents = file:read( “*a” )
io.close(file)
local world,pos,msg = json.decode( contents )
if not world then print(“load world”,wi,“fail at”,pos…":",msg) end
return world
end

Worked right away; what’s left to do is change the syntax of my level-description files from Lua to JSON: key=… becomes “key”:… , and [ ] for arrays…

I’m having fun discovering Lua with Solar2D !
-ivec