TL;DR: use require(), sol.main.load_file() is too low-level for most purposes.
The loadfile() vs require() choice is a pure Lua matter, there is nothing special in Solarus. (The sol.main.load_file() of Solarus is completely identical to loadfile() except that it loads relative to the data directory of archive.)
Here is how to properly call some code from another script, for example with a game parameter:
The other script (let's call it my_feature.lua):
local my_feature = {}
function my_feature:my_function(game)
-- Do stuff
end
return my_feature
The calling code (wherever you have your game object, typically in the game_manager script):
local my_feature = require("my_feature")
.........
-- Later:
local game = ............
.........
my_feature:my_function(game)
sol.main.load_file() / loadfile() is a very low-level function that opens a script, parses it and returns it as a function value. require() is much more powerful. require() is the recommended way because it does not load again and does not parses again the script, it only does that the first time. Subsequent calls to require() just return whatever the script returned the first time. In this example, the my_feature table.
It is the convention in Lua to return a table from required scripts. Lua programmers are used to this. But if you prefer, you can directly return a function instead of a table containing functions. This way you will have something similar to sol.main.load_file(). It would work like this:
The required script:
local function my_function(game)
-- Do stuff
end
return my_function
Or even
return function(game)
-- Do stuff
end
The calling code:
local my_function = require("my_function")
.........
-- Later:
local game = ............
.........
my_function(game)
Pros:
- The code is shorter.
Cons:
- It is less conventional to return a function from required scripts.
- Returning a table instead allows to put several functions in the table.
You can read this for more information about require() vs loadfile():
http://stackoverflow.com/questions/34235540/whats-the-difference-between-loadfile-require-and-import