CSci 450/503: Programming Languages
Modules in Lua

H. Conrad Cunningham

19 September 2016

Note: I corrected a few formatting errors on 29 January 2020.

Acknowledgements: These slides are adapted from

Advisory: The HTML version of this document may require use of a browser that supports the display of MathML. A good choice as of January 2020 is a recent version of Firefox from Mozilla.

MODULES IN LUA

Building Larger Programs

Module

Goals of Modularization

  1. enable programmers to understand the system by focusing on one module at a time (comprehensibility)

  2. shorten development time by minimizing required communication among groups (independent development)

  3. make system flexible by limiting number of modules affected by significant changes (changeability)

Information Hiding Module

Module Interface

Interface:

Abstract Interface for Module

Abstract interface:

Information hiding with abstract interfaces supports software reuse

Criteria for Good Interfaces (1)

Cohesion:
Fit all operations together to support single, coherent purpose
Consistency:
Provide internally consistent set of operations (naming, arguments, return, behavior) – avoid surprises!
Simplicity:
Avoid needless features
No redundancy:
Avoid offering same service in multiple ways

Criteria for Good Interfaces (2)

Atomicity:
Do not combine several operations if needed individually – each primitive, not decomposable into others
Completeness:
Include all primitive operations that make sense for abstraction
Reusability:
Make general for use beyond initial context
Robustness:
Keep interface stable even if implementation changes

Criteria for Good Interfaces (3)

Convenience:
Provide additional operations for user convenience – after careful study

Lua Module

Lua Module Design Principles

Using Lua Modules

A Simple Module

Can develop stub for complex number module, store in file complex.lua

    local M = {}          -- create the module's table
    function M.new(r, i)  -- could be: M.new = function(r, i)
        return { real = r or 0, im = i or 0 } 
    end 
    
    M.i = M.new(0, 1) 
    
    function M.add(c1, c2) 
        return M.new(c1.real + c2.real, c1.im + c2.im) 
    end 

    function M.tostring(c) 
        return tostring(c.real) .. "+" .. tostring(c.im) .. "i" 
    end 

    return M -- table with closures for keys "new", "add", "tostring"
             -- also constant value for "i"

Another Style Module

Loading Complex Module

Using Complex Module

Search Path