What is a way to reload lua scripts during run-time?
I want to reload lua scripts at run-time. What are the ways to do this? Do you just 开发者_运维百科have to reinitialize the lua system and then re-read all the lua files?
If (a) the Lua scripts are in modules, and (b) the modules don't affect globals or tables outside the scope of the module, you can use package.loaded.????? = nil
to cause require
to reload the module:
> require "lsqlite3"
> =sqlite3.version
function: 0x10010df50
> sqlite3.version = "33"
> return sqlite3.version
33
> require "lsqlite3"
> return sqlite3.version
33
> package.loaded.lsqlite3 = nil
> return sqlite3.version
33
> require "lsqlite3"
> return sqlite3.version
function: 0x10010c2a0
>
Similarly, if the non-module scripts are well behaved in that they (a) only define a single table, and (b) don't affect globals or other tables, then simply reloading the script will work as well.
Just use your own include(filename)
function:
function evalfile(filename, env)
local f = assert(loadfile(filename))
return f()
end
function eval(text)
local f = assert(load(text))
return f()
end
function errorhandler(err)
return debug.traceback(err)
end
function include(filename)
local success, result = xpcall(evalfile, errorhandler, filename)
--print(string.format("success=%s filename=%s\n", success, filename))
if not success then
print("[ERROR]\n",result,"[/ERROR]\n")
end
end
function include_noerror(filename)
local success, result = xpcall(evalfile, errorhandler, filename)
--print(string.format("success=%s filename=%s\n", success, filename))
end
精彩评论