GRUB 2 has integrated Lua as an alternative script engine. Apparently available in SVN (rev 2218) since May 16, 2009.
As of 2009-09-26 Lua is not anymore in official GRUB. It has moved to grub-extras now.
Enter/Exit Lua mode from command line
To enter Lua from command line, use the following command:
parser.lua
Now command prompt would change from "sh:grub > " to "lua:grub > " to indicate the current script engine is Lua. To switch back to sh mode, use the following Lua command:
grub.run("parser.sh")
Run Lua scripts
GRUB 2 support the use of #! to specify parser for current file. At the end of the script, it would switch back to default parser automatically. You can use this feature to run Lua script from the main configuration file grub.cfg. For example:
grub.cfg:
configfile hello.lua echo hello from sh
hello.lua:
#!lua
print("hello from lua")
GRUB library
The GRUB library allows accessing GRUB facilities from Lua. Currently, it contains the following functions:
grub.run
Execute a GRUB command, which is passed as a single string. Return grub_errno, the error message is returned as second value if grub_errno is not 0.
Example:
err_no,err_msg = grub.run("ls /")
print(err_no,err_msg)
grub.getenv
Get GRUB environment variable. Allow multiple input.
Example:
prefix,root = grub.getenv("prefix", "root")
grub.setenv
Set GRUB environment variable.
Example:
grub.setenv("aa", "Hello")
grub.run("set")
Examples
hanoi tower
Here is a script to solve the hanoi problem, it shows basic Lua constructs such as variable, assignment, control structure and (recursive) function.
hanoi.lua:
#!lua
function hanoi(n,a,b,c)
if (n == 1) then
print("move from", a, "to", c)
else
hanoi(n-1, a, c, b)
hanoi(1, a, b, c)
hanoi(n-1, b, a, c)
end
end
hanoi(3, 1, 2, 3)
season
Here is a script to demonstrate the interaction between Lua and GRUB. It uses date hook to get the current month, then calculate the season. You can do other tricks based on this, for example, using a different background image for each season.
season.lua:
#!lua
grub.run("insmod datehook")
m = tonumber(grub.getenv("MONTH"))
if (m >= 3) and (m <= 5) then
print("spring")
elseif (m >= 6) and (m <= 8) then
print("summer")
elseif (m >= 9) and (m <= 11) then
print("autumn")
else
print("winter")
end
Lua Reference
Complete reference to Lua language [http://www.lua.org/manual/5.1/]