Functions and multiple Lua scripts

Started by
1 comment, last by Sneftel 18 years, 8 months ago
If I've got several Lua script files, with different functions in each one, can I do lua_dofile() on each script just once and then call functions in both scripts, or do I have to call lua_dofile() each time I want to call a function in a different script?
I like the DARK layout!
Advertisement
Quote:Original post by BradDaBug
If I've got several Lua script files, with different functions in each one, can I do lua_dofile() on each script just once and then call functions in both scripts, or do I have to call lua_dofile() each time I want to call a function in a different script?


As long as you use the same Lua state, you can lua_dofile() on many files, and then call functions as if they were all in one file (everything that happens in the scripts will be applied to the Lua state: variables/tables and/or functions of the same name will get redefined in subsequent scripts). You can also dofile() from Lua scripts.

Understand that a "script" is really just a function. Suppose that you have a file test.lua that looks like this:
function printsomething(t)    print(t)end

..and you call "lua_dofile" on that file. Now what happens is that the file is read as a function taking no arguments. Also keep in mind that "function foo() ..." is really just a fancy way of saying "foo = function() ...". In other words, it's an assignment statement, which assigns a variable in the global table.
function toplevelfunctionwhichisexecuted()    printsomething = function(t)        print(t)    endend

So, of course, any changes to the global table are still left around after the file is done executing.

This topic is closed to new replies.

Advertisement