It is currently June 18th, 2024, 2:32 pm

Can global variables/tables from other scripts be imported with dofile()? (Also localization methods)

Discuss the use of Lua in Script measures.
Crest
Posts: 139
Joined: August 16th, 2013, 12:47 pm

Re: Can global variables/tables from other scripts be imported with dofile()?

Post by Crest »

nek wrote: May 25th, 2023, 8:01 pm An example of dealing with Lua metatable and language translations. for someone who are interested in.
Nice and succinct :thumbup: I'll have to look further into if this method could also be used to parse table values via their name passed to the main script, or even concatenating existing values. (In my case I've been using tables so that I can loop through lists of related localized strings and concatenate them into a value that's then returned but I could alternatively concatenate them without tables).

I think I'll also update the thread title if I can to reflect there are some useful localization methods within.
Crest
Posts: 139
Joined: August 16th, 2013, 12:47 pm

Re: Can global variables/tables from other scripts be imported with dofile()? (Also localization methods)

Post by Crest »

Just wanted to share a way I realized that globals can be quasi-imported from another script, since that was the original topic question.

If the script being imported via dofile() has a function and that function is called by the script that's importing it, then that function can call Initialize() and all the globals from the imported script will become defined in the script that imported it.

Overview:

- Main.lua imports 2ndScript.lua via dofile()
- 2ndScript.lua has globals defined within it's own version of Initialize().
- 2ndScript.lua also has separate function, let's call it ImportedFunc().
- Within ImportedFunc() it calls Initialize().

- Main.lua then calls ImportedFunc() and upon doing so all the globals from 2ndScript.lua become defined/usable in Main.lua.



Keep in mind, in the case of the method from the OP (that uses getfenv() as a stand-in for _G), globals are only needed since strings passed to the script that represent the table/key names can't be parsed otherwise as the method doesn't work on local variables (though in the simple OP example I'm only using a plain variable rather than parsing a table/key name).