Tips and Techniques

This section presents some tips and techniques that can prove useful when programming in XLua. Expect it to grow over time.


Global Variables via Datarefs

When using one Lua file per module, you cannot share variables between modules. You can; however, create a custom dataref in one module and then fetch that dataref from all the other modules that need that value. We'll refer to such a dataref as a global var dataref. This is limited to numbers and strings only. Lua tables cannot be shared between modules. If other modules need to be able to modify the "global var dataref", then you will need to create a Custom Write Dataref. If other modules only need to reference the global var dataref and not modify it, then a Read Only custom dataref is sufficient.


Global Lua Symbols

By symbols, we basically mean anything with a declared name: A function, a Lua table, a variable, etc. XLua does not allow sharing of symbols between modules; therefore, the only way to share symbols between Lua files is to utilize Lua's dofile function, which if you are familiar with C/C++, is essentially the same as #include.

For this case, we recommend you create one module only, and in the module file, only dofile other Lua files. This means that you will have two Lua files at minimum. one module file and another Lua file that is "called" from that file. As you add new Lua files to the project, you simply add dofile lines in the module file to load those files. Recall that Lua files are loaded in the order you dofile them. So any symbols that you need to be global to the project and available to other Lua files, you need to dofile first.