Greg
Greg

Reputation: 34838

can I dynamically load a lua file within Corona? (e.g. load level23.lua, from within my main game storyboard file)

Is it possible to dynamically load a lua file? e.g. loading the next level?

Background: * Have a storyboard based little game * Was going to have a different storyboard file for each level, but then the dynamics/code is exactly the same, so I thought I would load the level background/objects from a separate file dynamically. E.g. I could have level_1.lua, level_2.lua, etc. And within these files they could create (in lua) their whole set of background / interaction objects etc, and pass back to the main game storyboard file as one display object * Worked fine with a "require level_1", but now trying to make this dynamic I may be hitting an issue

If it's not possible any suggestions?

Upvotes: 1

Views: 1748

Answers (3)

Rob Miracle
Rob Miracle

Reputation: 3063

Corona SDK does let you require modules when needed, but this is different that dynamically loading modules at run time. Things loaded with the require statement are compiled at build time. You cannot later, download a .lua file and included it. Apple specifically prohibits this behavior.

But if your end goal is to follow the DRY principle (Don't Repeat Yourself), and have one set of code instead of duplicating it a bunch of times, if you can either one really big table with all your level data it in, or you can save each individual's data out to JSON formatted text files, and then read them back in on a level by level basis. You can't have executable code or formulas in there, but you can have image names, x, Y coordinates, physics properties, etc.

Upvotes: 2

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57625

require is a function taking a string, nothing more, nothing less. The fact that you don't use parenthesis is just syntactic sugar only applicable if the string is constant. If you run it as a normal function, you can do anything you want with the string:

module = require( "level_"..level_number )

...or...

levels = { "castle", "castle2", "boss" }
module = require( levels[level_number] )

Etc, etc...

Upvotes: 5

daven11
daven11

Reputation: 3035

if loadfile() doesn't work in corona you could perhaps use require since it works

e.g.

if level == 1 then
  game = require "level1"
else
  game = require "level2"
end

I believe you can use require anywhere, from http://www.lua.org/pil/8.1.html

Lua offers a higher-level function to load and run libraries, called require. Roughly, require does the same job as dofile, but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work. Because of these features, require is the preferred function in Lua for loading libraries.

Upvotes: 2

Related Questions