Skip to main content

Importing other scripts

You can import and use any Lua script (files with .lua extension) that you place directly under the Assets folder or other subdirectories with obvious exceptions of MLSDK and GIZMOS folder.

To import a Lua script, you can use the LUA.Import("scriptName") command. The scriptName is the name of the Lua script without the extension. So, for example to import an script named library.lua, use LUA.Import("library");

note

Do not include any directory name inside the scriptName.

Example

Let's have a Lua script file with we store some of the most used functions in it.

library.lua
function Factorial(n)
if (n == 0) then
return 1
else
return n * factorial(n - 1)
end
end

We can utilize use the factorial function in other scripts by importing it.

myScript.lua
do
LUA:Import("library");

local script = LUA.Script;

function script.Start()
Debug:Log( Factorial(5) );
end
end

Import considerations and limitations

Scope

Due to the scoping in the Lua, importing a script makes it available in every other script, so technically if a script is imported once, there is no need to import it again. However, this makes it confusing.

To address this, we recommend wrapping the libraries into an object and return it in the script. When something is returned in an imported script, the Import function actually returns the reference to that object.

Take a look at the example bellow:

library.lua
return { -- create and return an object
Factorial = function(n) -- factorial is a member of this object
if (n == 0) then
return 1
else
return n * factorial(n - 1)
end
end
}

And this object can be accessed using the import function and used:

myScript.lua
do
local math = LUA:Import("library"); -- getting the object

local script = LUA.Script;

function script.Start()
Debug:Log( math.Factorial(5));
end
end

Naming

Each Lua script must have a unique name. The name of the Lua file defines the script and how it can be accessed therefore two Lua Scripts with the same name are not allowed, even if they are in different subdirectories.