Loading Code Modules Dynamically
Lua makes it easy to load and unload code modules on the fly, to save memory or to provide program extensions.
The loadScript(<file>) function will load a script from a the file and return a function that is the body of the script, as described in the previous section. So you could have the following Lua script file saved on the SD card:
1
-- /SCRIPTS/TestScript.lua
2
local c = ...
3
4
local function f(x)
5
return x + c
6
end
7
8
return f
Copied!
You can load and use the above file with the following code:
1
local chunk = loadScript("/SCRIPTS/TestScript.lua")
2
3
local f1 = chunk(1)
4
local y = f1(5)
5
-- y = 5 + 1
6
7
local f2 = chunk(3)
8
local z = f2(5)
9
-- z = 5 + 3
Copied!
So here we put together what we learned in the previous section. The body of the script is an anonymous function returned by loadScript and stored in the variable chunk. It returns the function f when it is called. The local variable c in the script is assigned to the first vararg passed to the call. Since a new closure is created every time we call chunk, f1 and f2 have different closures with different values of c.
Export as PDF
Copy link