Scripting Best Practices

Modules

Modules have been depreciated by the Lua committee as they expose too much and create a number of global variables that programmers may not be aware of.
Solution? Rather than using require ‘moduleName’ to call a module and its associate functions, include the following variable in your script: local exampleModule = require ‘moduleName’.

This technique requires that you call the module functions exampleModule.foo rather than moduleName.foo.

This technique also requires that you set up your module a little differently:

-- define a local table to hold all of the references to functions and variables

local moduleTable = {}

-- create a local function
-- NOTE: "moduleTable.foo()" is local because it is an element in a local table (moduleTable)

function moduleTable.foo (fname, lname)
 -- script goes here
end

-- Create the a table for customized help
local addFooHelp = {
       Title="foo";
       Usage="moduleTable.foo('John', 'Doe')";
       Desc="This will do something with a first and last name. It will be awesome.";
       Returns= {
          {Desc="Awesome Number(will be negative if failed 'integer'"},
          {Desc="Optional error message 'string'"}
       };
       ParameterTable= true,
       Parameters= {
           {fName= {Desc="The given name or first name of the patient John, Mary etc."}},
           {lName= {Desc="Family name of the patient - i.e. Smith"; Opt=false}},
       };
       Examples={
           "e.g. local PatientId, Status = moduleTable.foo('John', 'Doe')"     
       };
       SeeAlso={
           {
               Title="Patient foo stuff operations.",
               Link="http://mydomain/my_extra_help.html"
           }
       }
   }

-- call the custom help functions for autocompletion support
help.set{input_function=moduleTable.foo,help_data=addFooHelp}

--return the table to be used locally.
return moduleTable

Note: This script also contains the required support elements for both customized help and customized auto-completion.

Modules are usually situated in the global name space; however, this technique keep them in the local name space includes in the table. The result? This script is faster to execute and encounters fewer memory issues. This technique also prevents confusion between the names of modules and the names of variables.

Note: Remember that module names should be intuitive to the functions that are included inside of it.

Tagged:

Leave A Comment?