lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Fri, May 13, 2011 at 08:40, Graham Nicholls <> wrote:
> I’d like to be able to ask the application to reload a particular (or all)
> files.
> I suspect that I’m looking in all the wrong places, but is there a lua
> function to “reload myself”?

It all depends. If you have loaded the script via require, you have to
remove if from package.loaded:

require 'myscript'

-- do stuff

if should_reload( 'myscript' ) then
    package.loaded[ 'myscript' ] = nil
    require 'myscript'

If you didn't use require, just "dofile 'myfile.lua'" again.

However, if your new script depends on a particular state to be
loaded, or other scripts have reference for it, then this may not be
that simple to implement.

For instance, if myscript.lua register a particular global value, and
a second script overwrites it, when myscript.lua reloads, the variable
will be reset. This can lead to mysterious and hard to reproduce bugs.

Another case is when the script was require'd to a local:

-- myawesomescript.lua
return { a = 1, b = 2 }

-- filea.lua
local script = require 'myawesomescript'

function TEST() print( script.a .. ' ~ ' .. script.b ) end

> TEST() --> 1 ~ 2

-- change myawesomescript.lua to:
return { a = 3, b = 4 }

-- reload and run
package.loaded[ 'myawesomescript' ] = nil
require 'myawesomescript'

TEST() --> 1 ~ 2  -- filea.lua still reference the old script

local foo = require 'myawesomescript'
print( foo.a, foo.b ) -- > 3     4

-- end of examples

This particular problem can be solved if you:

a. update the reference of your local to the new script value, but
this may not be pratical if you have many files with such
b. use global variables or other form of namespace (like a global
"modules" table: modules.myscript = require 'myscript' )
c. don't return any values from your script, just create global/shared
values (this is almost the same as b)

Without more info about your system I can't help you any further.