Reboot the system through Lua Script

I need to reboot the system through Lua Script. I need to write some line before the reboot happens, and you need to write the line in Lua script after the reboot is complete.

Example:

print("Before Reboot System") Reboot the System through Lua script print("After Reboot System") 

How to do it?

+4
source share
2 answers

You can use os.execute to issue system commands. For Windows it is shutdown -r , for Posix systems it is just reboot . Therefore, your Lua code will look like this:

Remember that part of the reboot command stops active programs, such as your Lua script. This means that any data stored in RAM will be lost. You need to write any data that you want to save to disk using, for example, serialization of tables .

Unfortunately, not knowing about the environment, I cannot say how to call the script again. You could add a call to the script at the end of ~/.bashrc or similar.

Make sure that loading this data and starting at a certain point after calling the reboot function is the first thing you do when you return! You do not want to go in cycles in an infinite reboot cycle when the first thing your computer does when it is turned on is to shut down. Something like this should work:

 local function is_rebooted() -- Presence of file indicates reboot status if io.open("Rebooted.txt", "r") then os.remove("Rebooted.txt") return true else return false end end local function reboot_system() local f = assert(io.open("Rebooted.txt", "w")) f:write("Restarted! Call On_Reboot()") -- Do something to make sure the script is called upon reboot here -- First line of package.config is directory separator -- Assume that '\' means it Windows local is_windows = string.find(_G.package.config:sub(1,1), "\\") if is_windows then os.execute("shutdown -r"); else os.execute("reboot") end end local function before_reboot() print("Before Reboot System") reboot_system() end local function after_reboot() print("After Reboot System") end -- Execution begins here ! if not is_rebooted() then before_reboot() else after_reboot() end 

(Warning - untested code. I did not want to reboot. :)

+6
source

There is no way in Lua to do what you ask. You may be able to do this with os.execute depending on your system and setup, but the Lua libraries only include what is possible in standard c libraries that do not include operating system-specific functions such as restarting.

+2
source

Source: https://habr.com/ru/post/1343950/


All Articles