ZZ_Require_in_NIL - jpbubble/NIL-isn-t-Lua GitHub Wiki
NOTE!
As of version 12.08.26, NIL supports the "#require" directive which works similar as "#use" only then with the Lua "require" instruction. Use that in stead if you can. The chapter about "#use" contains more information.
This document may be removed soon!
====
In Lua it's common when you use 3rd party content to use "require" for that like this:
MyModule = require "MyModule"
For NIL this practice is not recommended, and it can be better to use the "#use" tag in stead, which can be used with both NIL and Lua files, no issue there, but some files are really not set up to be imported with "#use", and modules written in C (or any other language exported to machine language for that matter which Lua will also assume to be C) are not compatible at all with "#use" and then you'll have to rely on 'require'.
NIL still supports this, like this:
var MyModule
MyModule = require "MyModule"
There are a few rubs though, that one should NEVER forget!
If a Lua Module is written like this (which is actually what most users expect) no problemo:
local MyModule = {}
function MyModule:MyMethod1()
end
function MyModule:MyMethod2()
return MyModule
If a Lua module is written like this, prepare for disaster in NIL:
function MyModuleFunction1()
end
function MyModuleFunction2()
end
This is because "require" doesn't enable NIL to check the contents of the file in question. The reason the first (and considered right) setup works is because everything is put in a table which is returned into a variable NIL already knows, the second script keeps all definitions to Lua itself and NIL will never know about it.
Possible solutions are these:
- You can make a separate Lua file with the "require" request in it and import that file in NIL with the "#use" directive and all contents of the file called with "require" are updated in the process
- You can also add "#accept" tags for all functions and global vars inside the module in your NIL file so NIL can see it, making these tags act a bit like a ".h" file in C.
Neither of these methods are perfect, but at least they get the job done.