Functions and multiple Lua scripts

This topic is 4911 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

Share on other sites
Quote:
 Original post by BradDaBugIf 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.

Share on other sites
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.

• What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 28
• 16
• 10
• 10
• 11
• Forum Statistics

• Total Topics
634111
• Total Posts
3015573
×