MediaWiki Extension:Lua
- MediaWiki Extension:Lua - A Beginner's Guide
The MediaWiki Extension:Lua is a powerful tool that significantly expands the capabilities of your wiki. It allows you to embed code written in the Lua scripting language directly within wiki pages, enabling dynamic content, complex calculations, and intricate functionality that would be difficult or impossible to achieve using only standard wiki markup and templates. This article provides a comprehensive introduction to the extension, covering its benefits, installation, basic usage, advanced concepts, and practical examples. It’s aimed at users with little to no prior experience with Lua or scripting in a MediaWiki environment.
What is Lua?
Lua (pronounced "loo-ah") is a lightweight, embeddable scripting language. It's designed for extensibility and is often used to add scripting capabilities to other applications. Its key features include:
- **Simplicity:** Lua has a relatively small core and a clean syntax, making it easier to learn than many other scripting languages.
- **Efficiency:** Lua is known for its speed and low memory footprint.
- **Embeddability:** Lua is designed to be easily integrated into applications written in other languages like C/C++, and now, MediaWiki.
- **Flexibility:** Lua is a dynamically typed language, offering a high degree of flexibility in how you write your code.
For MediaWiki, Lua provides a way to overcome the limitations of the wiki's native templating system, which can become cumbersome and slow when dealing with complex logic or large datasets. It allows administrators and developers to create highly customized and sophisticated features without modifying the core MediaWiki code. Understanding Parser functions is helpful, but Lua offers a substantially more powerful alternative.
Why Use Lua in MediaWiki?
Several compelling reasons exist to integrate Lua into your MediaWiki installation:
- **Enhanced Template Functionality:** Lua allows you to create templates that perform complex calculations, manipulate strings, and interact with external data sources. This is particularly useful for things like financial calculators, game statistics, or data visualization.
- **Dynamic Content Generation:** Lua can generate content dynamically based on user input, database queries, or other factors. This enables features like personalized dashboards, interactive forms, and real-time data displays. Consider applications in Dynamic content.
- **Improved Performance:** For computationally intensive tasks, Lua code can often execute much faster than equivalent logic written in wiki templates. This is because Lua is a compiled language, while wiki templates are interpreted.
- **Code Reusability:** Lua code can be organized into modules and reused across multiple wiki pages and templates, promoting code maintainability and reducing redundancy. This is similar to the benefits of Modules.
- **Access to External Libraries:** Lua can be extended with external libraries, providing access to a wide range of functionalities, such as data analysis, image processing, and network communication.
- **Complex Data Structures:** Lua handles tables (associative arrays) effectively, enabling the management of complex datasets that are difficult to represent using standard wiki markup. This is essential for Data management.
Installation and Configuration
Installing the Lua extension requires server access and basic familiarity with MediaWiki extension management.
1. **Download the Extension:** Download the latest version of the Lua extension from the [MediaWiki Extensions repository](https://www.mediawiki.org/wiki/Extension:Lua). 2. **Upload the Files:** Upload the extracted extension files to the `extensions` directory of your MediaWiki installation. 3. **Configure `LocalSettings.php`:** Add the following line to your `LocalSettings.php` file:
```php wfLoadExtension('Lua'); ```
4. **Enable Scribunto:** The Lua extension relies on the Scribunto extension for sandboxing and security. Scribunto should be automatically installed as a dependency of Lua, but ensure it is enabled in `LocalSettings.php` as well.
```php wfLoadExtension('Scribunto'); ```
5. **Configure Scribunto (Optional):** Scribunto has several configuration options that can be set in `LocalSettings.php`, such as the maximum execution time and memory limit for Lua scripts. Consult the [Scribunto documentation](https://www.mediawiki.org/wiki/Extension:Scribunto) for details.
6. **Restart MediaWiki:** After making these changes, restart your MediaWiki installation for the extension to take effect. This usually involves restarting the web server or clearing the MediaWiki cache.
Basic Usage: Calling Lua from Wiki Pages
Lua code is executed within MediaWiki pages using the `#invoke` parser function. The basic syntax is as follows:
```wiki {{#invoke:ModuleName|FunctionName|arg1|arg2|...}} ```
- `ModuleName`: The name of the Lua module where the function is defined. Module names are case-sensitive.
- `FunctionName`: The name of the Lua function to be called within the module.
- `arg1`, `arg2`, ...: Any arguments that need to be passed to the Lua function. These arguments are passed as strings.
To create a Lua module, you need to create a subpage of the `Module:` namespace. For example, to create a module named `Module:MyModule`, you would create a page titled `Module:MyModule`.
Here's a simple example:
- Module:MyModule**
```lua function greet(name)
return "Hello, " .. name .. "!"
end ```
- Wiki Page**
```wiki {{#invoke:MyModule|greet|World}} ```
This will display "Hello, World!" on the wiki page.
Advanced Concepts
- **Lua Tables:** Lua tables are the primary data structure. They are associative arrays, meaning they can store key-value pairs where the keys can be any value except `nil`. Tables can be used to represent arrays, dictionaries, objects, and more.
- **Lua Functions:** Functions are blocks of code that perform specific tasks. They can take arguments and return values.
- **Lua Modules:** Modules are files that contain Lua code. They are used to organize code into reusable units. Each module resides on a subpage of the `Module:` namespace.
- **`mw` object:** The `mw` object is a global variable that provides access to MediaWiki-specific functions and data. It allows Lua code to interact with the wiki environment. Important functions include:
* `mw.title.new(title)`: Creates a `Title` object representing a wiki page. * `mw.text.escape(text)`: Escapes special characters in a string for safe display in a wiki page. * `mw.ustring`: Provides functions for string manipulation (similar to `string` in standard Lua, but handles Unicode correctly).
- **Error Handling:** Lua provides error handling mechanisms, such as `pcall`, which allows you to call a function and catch any errors that occur. Proper error handling is crucial for preventing Lua scripts from crashing the wiki.
- **Sandboxing:** Scribunto provides a secure sandbox environment for executing Lua code. This prevents Lua scripts from accessing sensitive data or modifying the wiki system. Understanding the limitations of the sandbox is important.
Practical Examples
Here are some more advanced examples to illustrate the power of Lua in MediaWiki:
- 1. Calculating Fibonacci Numbers:**
- Module:Fibonacci**
```lua function fibonacci(n)
if n <= 1 then return n else return fibonacci(n - 1) + fibonacci(n - 2) end
end ```
- Wiki Page**
```wiki The 10th Fibonacci number is: {{#invoke:Fibonacci|fibonacci|10}} ```
- 2. Converting Temperatures:**
- Module:TemperatureConverter**
```lua function celsius_to_fahrenheit(celsius)
return (celsius * 9/5) + 32
end
function fahrenheit_to_celsius(fahrenheit)
return (fahrenheit - 32) * 5/9
end ```
- Wiki Page**
```wiki 25 degrees Celsius is equal to {{#invoke:TemperatureConverter|celsius_to_fahrenheit|25}} degrees Fahrenheit. ```
- 3. Displaying a Table of Data (Example: Stock Prices)**
- Module:StockData**
```lua local stock_prices = {
["AAPL"] = 170.34, ["GOOG"] = 2700.50, ["MSFT"] = 330.75,
}
function get_stock_price(symbol)
return stock_prices[symbol]
end ```
- Wiki Page**
```wiki
Stock Symbol | Price |
---|---|
AAPL | get_stock_price|AAPL}} |
GOOG | get_stock_price|GOOG}} |
MSFT | get_stock_price|MSFT}} |
```
- 4. Implementing a Simple Trading Strategy Indicator (Example: Moving Average)**
- Module:MovingAverage**
```lua function calculate_moving_average(data, period)
local sum = 0 for i = 1, period do sum = sum + data[i] end return sum / period
end ```
- Wiki Page (assuming 'data' is a comma-separated list of numbers)**
```wiki Data: 10, 12, 15, 14, 16, 18, 20 5-day Moving Average: {{#invoke:MovingAverage|calculate_moving_average|10,12,15,14,16,18,20|5}} ```
(Note: This is a simplified example. Real-world trading strategies are significantly more complex. See resources on Technical Analysis and Trading Strategies for more information.)
- 5. Implementing a Bollinger Bands Indicator (More complex)**
- Module:BollingerBands**
```lua function calculate_bollinger_bands(data, period, std_dev)
local moving_average = 0 for i = 1, period do moving_average = moving_average + data[i] end moving_average = moving_average / period
local standard_deviation = 0 for i = 1, period do standard_deviation = standard_deviation + (data[i] - moving_average)^2 end standard_deviation = math.sqrt(standard_deviation / period)
local upper_band = moving_average + (std_dev * standard_deviation) local lower_band = moving_average - (std_dev * standard_deviation)
return moving_average, upper_band, lower_band
end ```
- 6. Support Vector Machine (SVM) for Trend Prediction (Advanced - Requires External Libraries)**
Using external libraries available through Lua's package manager can enable more complex tasks like machine learning. However, this requires significant configuration and is beyond the scope of a beginner's guide. Consider researching Machine Learning in Finance for relevant libraries.
Best Practices
- **Keep Modules Small and Focused:** Each module should have a specific purpose.
- **Document Your Code:** Add comments to explain what your code does.
- **Use Meaningful Variable Names:** Make your code easier to understand.
- **Test Thoroughly:** Test your Lua code to ensure it works correctly and doesn't cause errors. Consider using Backtesting techniques for trading strategies.
- **Follow Security Best Practices:** Be aware of the limitations of the sandbox and avoid writing code that could compromise the security of your wiki.
- **Error Handling is Crucial:** Always include error handling to gracefully handle unexpected situations.
- **Optimize for Performance:** If your Lua code is slow, look for ways to optimize it. Profiling tools can help identify performance bottlenecks. Consider the impact of Algorithmic Complexity.
Resources
- **Lua Documentation:** [1](https://www.lua.org/docs.html)
- **Scribunto Documentation:** [2](https://www.mediawiki.org/wiki/Extension:Scribunto)
- **MediaWiki Extension:Lua:** [3](https://www.mediawiki.org/wiki/Extension:Lua)
- **Technical Analysis:** [4](https://www.investopedia.com/terms/t/technicalanalysis.asp)
- **Trading Strategies:** [5](https://www.investopedia.com/terms/t/trading-strategy.asp)
- **Moving Average:** [6](https://www.investopedia.com/terms/m/movingaverage.asp)
- **Bollinger Bands:** [7](https://www.investopedia.com/terms/b/bollingerbands.asp)
- **Fibonacci Retracement:** [8](https://www.investopedia.com/terms/f/fibonacciretracement.asp)
- **Support and Resistance Levels:** [9](https://www.investopedia.com/terms/s/supportandresistance.asp)
- **Candlestick Patterns:** [10](https://www.investopedia.com/terms/c/candlestickpattern.asp)
- **Relative Strength Index (RSI):** [11](https://www.investopedia.com/terms/r/rsi.asp)
- **MACD:** [12](https://www.investopedia.com/terms/m/macd.asp)
- **Stochastic Oscillator:** [13](https://www.investopedia.com/terms/s/stochasticoscillator.asp)
- **Volume Weighted Average Price (VWAP):** [14](https://www.investopedia.com/terms/v/vwap.asp)
- **Elliott Wave Theory:** [15](https://www.investopedia.com/terms/e/elliottwavetheory.asp)
- **Ichimoku Cloud:** [16](https://www.investopedia.com/terms/i/ichimoku-cloud.asp)
- **Trend Lines:** [17](https://www.investopedia.com/terms/t/trendline.asp)
- **Chart Patterns:** [18](https://www.investopedia.com/terms/c/chartpattern.asp)
- **Head and Shoulders Pattern:** [19](https://www.investopedia.com/terms/h/headandshoulders.asp)
- **Double Top/Bottom:** [20](https://www.investopedia.com/terms/d/doubletop.asp)
- **Triangles:** [21](https://www.investopedia.com/terms/t/triangle.asp)
- **Gap Analysis:** [22](https://www.investopedia.com/terms/g/gap.asp)
- **Divergence:** [23](https://www.investopedia.com/terms/d/divergence.asp)
- **Backtesting:** [24](https://www.investopedia.com/terms/b/backtesting.asp)
- **Algorithmic Complexity:** [25](https://www.investopedia.com/terms/a/algorithmic-complexity.asp)
- **Machine Learning in Finance:** [26](https://www.investopedia.com/articles/investing/111715/machine-learning-finance-applications.asp)
Help:Lua Help:Scribunto Manual:Templates Manual:Parser functions Extension:Scribunto Modules Dynamic content Data management Technical Analysis Trading Strategies Backtesting Algorithmic Complexity
Start Trading Now
Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)
Join Our Community
Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners