Help:Modules
- Help:Modules
Introduction
This page provides a comprehensive guide to using Modules within the MediaWiki environment, specifically tailored for beginners. Modules are a powerful feature introduced in MediaWiki 1.19 that allow for reusable code snippets, primarily written in the Lua scripting language, to be integrated into wiki pages. They drastically improve code maintainability, reduce duplication, and enable complex functionality that would be impractical or impossible with standard wiki markup. Understanding Modules is key to advanced wiki development and customization. This guide will cover the core concepts, how to create and use Modules, the benefits, and common pitfalls.
What are Modules?
At their core, Modules are self-contained files containing Lua code. These files reside in a special namespace – the `Module:` namespace – within the wiki. Think of them as mini-programs that can be called upon from wiki pages. Instead of writing the same complex calculation or formatting code repeatedly across multiple pages, you write it once in a Module and then *invoke* that Module whenever you need it.
Consider a scenario where you frequently need to display a formatted table of stock data, including calculations like moving averages and Relative Strength Index (RSI). Without Modules, you'd have to copy and paste the table markup and Lua code (if you were using parser functions with Lua) into every page. This is prone to errors, difficult to update, and makes your wiki code bloated. With Modules, you write the table formatting and calculations *once* in a Module (e.g., `Module:StockTable`), and then simply call `{{#invoke:StockTable|formatTable|symbol=AAPL|period=14}}` on each page where you want the table.
Why use Modules?
The benefits of using Modules are substantial:
- Reusability: The most significant advantage. Write code once, use it many times.
- Maintainability: If you need to change the logic of the stock table, you only modify the code in `Module:StockTable`. All pages using the Module automatically reflect the change.
- Organization: Modules help keep your wiki codebase organized. Complex logic is isolated from the main page content.
- Performance: While the initial load of a Module might take a bit longer, subsequent uses are cached, improving overall performance compared to repeatedly executing the same code in parser functions.
- Complexity: Modules allow for significantly more complex logic than is feasible with standard wiki markup or simple parser functions. This enables features like sophisticated data analysis, charting, and interactive elements.
- Collaboration: Modules can be developed and maintained by different users, promoting collaborative development.
- Testing: Modules can be tested independently, ensuring their correctness before deployment.
Basic Module Structure
All Modules are written in Lua. A typical Module file looks like this:
```lua local p = {} -- The module table. All functions and data will be added to this table.
-- Function to calculate a simple moving average (SMA) function p.calculateSMA(data, period)
local sum = 0 for i = 1, period do sum = sum + data[i] end return sum / period
end
-- Function to format stock data as a table function p.formatTable(frame, symbol, period)
-- Retrieve data from an external source (e.g., using #property) local data = {{10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}} -- Example data local sma = p.calculateSMA(data[1], period)
local output = "
\n" output = output .. "\n" output = output .. "\n" output = output .. "Symbol | SMA |
---|---|
" .. symbol .. " | " .. sma .. " |
\n"
return output
end
return p -- Return the module table ```
Let's break down the code:
- `local p = {}`: This creates a local table named `p`. This table will contain all the functions and data that the Module exports.
- `function p.calculateSMA(data, period)`: This defines a function named `calculateSMA` within the `p` table. This function calculates the Simple Moving Average.
- `function p.formatTable(frame, symbol, period)`: This defines a function named `formatTable`. This function takes a `frame` (which provides access to the calling wiki page's parameters), the stock `symbol`, and the `period` for the SMA calculation as input. It retrieves data, calculates the SMA, and formats it into an HTML table.
- `return p`: This line is crucial. It returns the `p` table, making its functions and data accessible from wiki pages.
Creating a Module
1. **Create the Page:** Navigate to `Module:<ModuleName>` (e.g., `Module:StockTable`) in your wiki. If the page doesn’t exist, click the "Create" button. 2. **Enter the Code:** Paste the Lua code into the page. 3. **Save the Page:** Save the page. The Module is now created.
Using a Module from a Wiki Page
You invoke a Module using the `#invoke` parser function. The syntax is:
```wiki {{#invoke:<ModuleName>|<FunctionName>|<arg1>|<arg2>|...}} ```
- `<ModuleName>`: The name of the Module you want to use (e.g., `StockTable`).
- `<FunctionName>`: The name of the function within the Module you want to call (e.g., `formatTable`).
- `<arg1>`, `<arg2>`, ...: The arguments to pass to the function. These can be named arguments (e.g., `symbol=AAPL`) or positional arguments.
Example:
```wiki {{#invoke:StockTable|formatTable|symbol=AAPL|period=14}} ```
This will call the `formatTable` function in the `Module:StockTable` Module, passing the `symbol` "AAPL" and the `period` 14 as arguments.
The `frame` Parameter
Most Module functions receive a `frame` parameter as their first argument. The `frame` object provides access to the context from which the Module was invoked. This allows you to:
- **Access Parameters:** Retrieve arguments passed from the wiki page using `frame.args`. For example, `frame.args.symbol` would access the value of the `symbol` parameter.
- **Access Title:** Get the title of the page the Module is being used on using `frame.title`.
- **Access the Parser:** Interact with the wiki parser.
Common Lua Concepts for Modules
- **Tables:** Lua's primary data structure. Used to store key-value pairs, arrays, and objects. We used a table `p` to hold the Module's functions.
- **Functions:** Blocks of code that perform specific tasks.
- **Variables:** Used to store data. `local` variables are scoped to the function they are defined in.
- **Control Structures:** `if` statements, `for` loops, `while` loops, etc., allow you to control the flow of execution.
- **Strings:** Textual data.
- **Numbers:** Numerical data.
Debugging Modules
Debugging Modules can be challenging. Here are some techniques:
- **`#invoke` with `debug=true`:** Adding `debug=true` as an argument to the `#invoke` function will print debugging information to the page. For example: `{{#invoke:StockTable|formatTable|symbol=AAPL|period=14|debug=true}}`.
- **`mw.log()`:** Use the `mw.log()` function within your Module to write messages to the wiki's error log. This is useful for more complex debugging.
- **Error Messages:** Pay close attention to any error messages displayed on the wiki page. These often provide clues about the source of the problem.
- **Syntax Highlighting:** Use a Lua syntax highlighter in your text editor to help identify syntax errors.
- **Incremental Development:** Build your Module in small steps, testing each step as you go.
Advanced Module Techniques
- **Submodules:** You can break down large Modules into smaller, more manageable submodules.
- **Module Data:** Store data within Modules for reuse. This can include configuration settings, lists of values, or other information.
- **Iterators:** Create custom iterators to process data in a more efficient way.
- **Templates as Modules:** You can convert existing templates into Modules for increased flexibility and maintainability.
- **Using External Libraries:** While limited, you can sometimes incorporate external Lua libraries into your Modules.
Strategies & Technical Analysis Integration
Modules can be used to implement and display a wide range of trading strategies and technical analysis indicators. Here are some examples:
- **Moving Averages:** Simple Moving Average (SMA), Exponential Moving Average (EMA), Weighted Moving Average (WMA). Moving Averages are fundamental tools for identifying trends.
- **Momentum Indicators:** Relative Strength Index (RSI), Stochastic Oscillator, Moving Average Convergence Divergence (MACD). Momentum Indicators help gauge the speed and strength of price movements.
- **Volume Indicators:** On Balance Volume (OBV), Accumulation/Distribution Line. Volume Indicators provide insights into buying and selling pressure.
- **Volatility Indicators:** Bollinger Bands, Average True Range (ATR). Volatility Indicators measure the degree of price fluctuation.
- **Chart Patterns:** Head and Shoulders, Double Top/Bottom, Triangles. Chart Patterns can signal potential reversals or continuations of trends.
- **Fibonacci Retracements:** Fibonacci Retracements are used to identify potential support and resistance levels.
- **Elliott Wave Theory:** Elliott Wave Theory attempts to identify recurring patterns in price movements.
- **Candlestick Patterns:** Candlestick Patterns provide visual cues about market sentiment.
- **Ichimoku Cloud:** Ichimoku Cloud is a comprehensive indicator that combines multiple elements to provide a holistic view of the market.
- **Pivot Points:** Pivot Points are used to identify potential support and resistance levels.
- **Support and Resistance Levels:** Support and Resistance are key levels where price tends to find support or encounter resistance.
- **Trend Lines:** Trend Lines are used to identify the direction of a trend.
- **Breakout Strategies:** Breakout Strategies capitalize on price movements that break through established levels.
- **Scalping Strategies:** Scalping Strategies aim to profit from small price fluctuations.
- **Day Trading Strategies:** Day Trading Strategies involve opening and closing positions within the same day.
- **Swing Trading Strategies:** Swing Trading Strategies aim to profit from short-term price swings.
- **Position Trading Strategies:** Position Trading Strategies involve holding positions for longer periods.
- **Mean Reversion Strategies:** Mean Reversion aims to profit from price movements that revert to the average.
- **Pair Trading Strategies:** Pair Trading involves identifying and exploiting discrepancies between two correlated assets.
- **Arbitrage Strategies:** Arbitrage aims to profit from price differences in different markets.
- **Risk Management Techniques:** Risk Management is crucial for protecting capital and minimizing losses.
- **Backtesting:** Backtesting involves testing a strategy on historical data to assess its performance.
- **Algorithmic Trading:** Algorithmic Trading involves using computer programs to execute trades automatically.
- **Market Sentiment Analysis:** Market Sentiment gauges the overall attitude of investors towards a particular asset.
- **Correlation Analysis:** Correlation measures the statistical relationship between two assets.
Security Considerations
- **Limit Permissions:** Only allow trusted users to edit Modules.
- **Sanitize Input:** Always sanitize any input received from wiki pages to prevent code injection attacks.
- **Avoid Sensitive Data:** Do not store sensitive data (e.g., passwords, API keys) directly in Modules.
Resources
- Help:Lua – The official MediaWiki help page for Lua scripting.
- Help:Extension:Scribunto – Information about the Scribunto extension, which enables Lua scripting in MediaWiki.
- Lua Official Website - The official Lua programming language website.
- Scribunto Documentation - Comprehensive documentation for Scribunto and Lua in MediaWiki.
Conclusion
Modules are a powerful tool for extending the functionality of your MediaWiki wiki. While they require some programming knowledge, the benefits in terms of reusability, maintainability, and complexity are well worth the effort. By following the guidelines in this article, you can start creating and using Modules to enhance your wiki and unlock its full potential.
Help:Table of Contents Help:Parser functions Help:Templates Help:Extension:Scribunto Help:Lua Help:Categories Help:Namespaces Help:Editing Help:Linking Help:Variables