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 run simply:
lua
Now the command prompt will change from "grub> " to "lua> ". Press the escape key to exit lua and return to grub's sh.
Run Lua scripts
To run lua scripts, you simply pass the script name to the lua command:
grub.cfg:
lua hello.lua echo hello from sh
hello.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:
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:
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/]