11

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?

2 Answers 2

22

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.