How to include a file only once?

Thalassicus

Bytes and Nibblers
Joined
Nov 9, 2005
Messages
11,057
Location
Texas
  • File A needs to include File B
  • File B needs to include File A
How do I do this? I basically need the equivalent of the c++ compiler's "ifndef" checks or "#pragma once" to ensure the include only happens once.
 
  • File A needs functions from File B
  • File B needs functions from File A
How do I include both these files without it looping? I basically need the equivalent of the c++ compiler's "ifndef" checks or "#pragma once" to ensure the include only happens once.

File C has the functions needed by both A and B and both A and B include C - only way I know of.

Oh, and by the way, the "include function" actually matches a pattern not a filename - see http://forums.2kgames.com/showthread.php?109126-Weirdness-in-the-VFS
 
Declarations of functions and variables and so on are all procedural, so I'd've thought you could check to see whether a key function of the file has been defined or not, and wrap the whole file's contents in a if check of this. Just like using the C preprocessor, except it evaluates based on real code.
 
@SamBC
When I tried that, I run into problems when files are in different contexts. One of the two utility files are included in several of the game's core user interface files. When I wrap things in a big "if X is defined do stuff end" like in c, problems arise between the mod files and other core game files, with bizzare errors like "setmetatable is nil" or the functions just not being available to other files.

The functions are defined as subtables of the LuaEvents global. I've also tried attaching them to the Game, Events, ModUserData, and other globals. When I last researched contexts, documentation was so scarce I couldn't figure out a good way to get things to work. I've currently got all the utility functions lumped together in one file like whoward69 mentioned... just wondering if anyone knows of an alternative that definitely works.
 
Shoot me a PM with the full problem. I had a similar issue working with ContextPtrs when developing the custom notification system.
 
I think I have a handle on how contexts should work - just the Lua docs don't call them contexts, they call them something else (that I can't remember right now). The main thing I think that's applicable to this problem for that is that you should probably have a clear separation between files that supply context-local functionality (and thus need to be included once per context that cares about them, and guards should do the trick), and files that provide inter-context functionality (ie register LuaEvent functions).
 
Back
Top Bottom