Lua scripting
- Lua Scripting for Beginners in MediaWiki
Lua is a powerful, fast, lightweight, embeddable scripting language. It’s increasingly important in the MediaWiki ecosystem, particularly with the advent of Extension:Scribunto, which allows developers and experienced users to extend MediaWiki's functionality in ways previously impossible through traditional wiki markup and templates. This article will serve as a comprehensive introduction to Lua scripting within the context of MediaWiki, aimed at beginners with little to no prior programming experience.
- What is Lua and Why Use it in MediaWiki?
Lua (pronounced "loo-ah") was originally designed in 1993 at PUC-Rio in Brazil as a configuration language for software. Its simple syntax, efficiency, and portability quickly led to its wider adoption. It's now used in a variety of applications, including game development (Roblox, World of Warcraft), embedded systems, web servers, and, crucially for us, MediaWiki.
Before Scribunto, MediaWiki's template system, while powerful, had limitations. Complex calculations, string manipulation, and conditional logic were difficult or impossible to implement effectively. Scribunto solved this by allowing Lua code to be executed within MediaWiki templates and modules. This unlocks a whole new level of customization and functionality.
Here's why you might want to learn Lua for MediaWiki:
- **Increased Template Capabilities:** Create templates that perform complex calculations, like those needed for Technical Analysis indicators or financial modeling.
- **Code Reusability:** Lua modules can be reused across multiple templates, promoting modularity and reducing redundancy.
- **Performance Improvements:** Lua is significantly faster than many alternative solutions for complex tasks within templates.
- **Enhanced Dynamic Content:** Generate dynamic content based on data, user input, or external sources.
- **Data Processing:** Manipulate and process data efficiently, which can be useful for creating dynamic tables or charts.
- **Integration with APIs:** Interact with external APIs to pull in real-time data, such as stock prices or weather information. This is vital for building tools that track Market Trends.
- Setting Up Your Environment
You don’t need a special editor to write Lua code for MediaWiki. Any plain text editor will work. However, using an editor with syntax highlighting can greatly improve readability and reduce errors. Popular options include:
- **Visual Studio Code:** With the Lua extension.
- **Sublime Text:** With the Lua package.
- **Notepad++:** With Lua syntax highlighting enabled.
Within MediaWiki, you’ll be writing Lua code in two main places:
- **Modules:** These are Lua files stored on the wiki. They are typically used to define functions and data that can be called by templates. Modules are created using the `Module:` namespace (e.g., `Module:MyModule`).
- **Templates:** Templates can call functions defined in modules to perform calculations or generate dynamic content.
You’ll need to ensure that Scribunto is installed and configured on your MediaWiki instance. This is usually handled by a system administrator. If you're using a hosted wiki, Scribunto is likely already enabled.
- Lua Basics: Syntax and Data Types
Let's start with the fundamental building blocks of Lua.
- Comments
Comments are used to explain your code and are ignored by the Lua interpreter. Use `--` for single-line comments.
```lua -- This is a comment. x = 10 -- Assign the value 10 to the variable x ```
- Variables
Variables are used to store data. In Lua, you don't need to declare variables explicitly. They are created when you first assign a value to them.
```lua x = 10 name = "Alice" ```
- Data Types
Lua has several built-in data types:
- **nil:** Represents the absence of a value.
- **boolean:** `true` or `false`.
- **number:** Represents both integers and floating-point numbers (e.g., 10, 3.14).
- **string:** Represents text (e.g., "Hello, world!"). Strings are enclosed in single or double quotes.
- **table:** The primary data structure in Lua. Tables are associative arrays, meaning they can store key-value pairs. They are incredibly versatile and used to represent arrays, dictionaries, and objects.
- **function:** Blocks of code that can be executed.
- **userdata:** Used to represent data stored in C/C++ libraries.
- **thread:** Represents an independent thread of execution (less common in MediaWiki).
- Operators
Lua supports various operators:
- **Arithmetic Operators:** `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `^` (exponentiation), `%` (modulo).
- **Comparison Operators:** `==` (equal to), `~=` (not equal to), `<` (less than), `>` (greater than), `<=` (less than or equal to), `>=` (greater than or equal to).
- **Logical Operators:** `and` (logical AND), `or` (logical OR), `not` (logical NOT).
- **String Concatenation:** `..` (concatenates strings).
- Control Structures
Control structures allow you to control the flow of execution in your code.
- **if-then-else:**
```lua if x > 10 then
print("x is greater than 10")
else
print("x is less than or equal to 10")
end ```
- **while loop:**
```lua i = 1 while i <= 5 do
print(i) i = i + 1
end ```
- **for loop:** Lua offers two types of for loops: numeric and generic.
* **Numeric for loop:**
```lua for i = 1, 5 do
print(i)
end ```
* **Generic for loop:** Used to iterate over tables.
```lua my_table = {"apple", "banana", "cherry"} for key, value in pairs(my_table) do
print(key, value)
end ```
- Working with Tables
Tables are the cornerstone of Lua programming. Let's explore how to create and manipulate them.
- Creating Tables
```lua -- Create an empty table my_table = {}
-- Create a table with initial values another_table = {1, 2, 3, "hello"}
-- Create a table with key-value pairs person = {
name = "Bob", age = 30, city = "New York"
} ```
- Accessing Table Elements
```lua -- Accessing elements using numeric indices (for arrays) print(another_table[1]) -- Output: 1
-- Accessing elements using keys (for dictionaries) print(person.name) -- Output: Bob print(person["age"]) -- Output: 30 ```
- Modifying Tables
```lua my_table[1] = "new value" person.age = 31 ```
- Table Functions
Lua provides several built-in functions for working with tables:
- `table.insert(table, value)`: Inserts a value into a table.
- `table.remove(table, pos)`: Removes an element from a table at a given position.
- `table.sort(table)`: Sorts the elements of a table.
- `table.concat(table, sep, i, j)`: Concatenates the elements of a table into a string.
- `pairs(table)`: Iterates over all key-value pairs in a table.
- `ipairs(table)`: Iterates over numeric indices in a table (suitable for arrays).
- Functions
Functions are reusable blocks of code.
- Defining Functions
```lua function greet(name)
print("Hello, " .. name .. "!")
end ```
- Calling Functions
```lua greet("Charlie") -- Output: Hello, Charlie! ```
- Returning Values
```lua function add(x, y)
return x + y
end
result = add(5, 3) print(result) -- Output: 8 ```
- Modules in MediaWiki
Modules are Lua files stored on the wiki. They are used to encapsulate reusable code and data.
- Creating a Module
1. Create a new page with the title `Module:MyModule`. 2. Add the following code to the page:
```lua local M = {} -- Create a table to hold the module's functions
function M.my_function(x)
return x * 2
end
return M ```
- Calling a Module from a Template
1. Create a new template (e.g., `Template:MyTemplate`). 2. Add the following code to the template:
```wiki {{#invoke:MyModule|my_function|{{{1}}}}} ```
3. Use the template on a wiki page: `Template:MyTemplate` This will output `10`.
- Practical Examples for Financial Applications
Let's look at some examples relevant to financial analysis and trading strategies.
1. **Simple Moving Average (SMA):**
```lua local M = {}
function M.sma(prices, period) local sum = 0 for i = 1, period do sum = sum + prices[i] end return sum / period end
return M ```
2. **Relative Strength Index (RSI):** Requires more complex calculations including average gains and losses. See resources like Investopedia RSI for the formula.
3. **Fibonacci Retracement Levels:** Calculating these levels from high and low prices. Fibonacci Retracement provides background information.
4. **Bollinger Bands:** Calculating upper and lower bands based on a moving average and standard deviation. Bollinger Bands Explained provides details.
5. **Profit/Loss Calculation:** Calculating profit or loss based on entry and exit prices, position size, and fees. Trading Profit/Loss offers a basic overview.
6. **Risk-Reward Ratio:** Calculating the risk-reward ratio based on potential profit and potential loss. Risk-Reward Ratio Analysis provides more detail.
7. **Position Sizing:** Determining the appropriate position size based on risk tolerance and account balance. Position Sizing Strategies can be helpful.
8. **Correlation Analysis:** Calculating the correlation between two assets. Correlation in Trading explains this concept.
9. **Volatility Calculation:** Measuring the volatility of an asset using standard deviation or other metrics. Measuring Volatility outlines different methods.
10. **Dynamic Support and Resistance Levels:** Identifying support and resistance levels based on price action and volume. Support and Resistance provides a foundational understanding.
11. **MACD (Moving Average Convergence Divergence):** A trend-following momentum indicator. MACD Indicator provides detailed information.
12. **Stochastic Oscillator:** Another momentum indicator. Stochastic Oscillator Explained gives a thorough explanation.
13. **Ichimoku Cloud:** A comprehensive indicator providing support, resistance, and trend direction. Ichimoku Cloud Trading is a good resource.
14. **Average True Range (ATR):** Measures market volatility. ATR Indicator details its use.
15. **Parabolic SAR:** Identifies potential reversal points. Parabolic SAR Indicator explains its mechanics.
16. **Williams %R:** A momentum indicator similar to the Stochastic Oscillator. Williams %R Indicator offers an explanation.
17. **Chaikin Money Flow:** Measures the amount of money flowing into or out of a security. Chaikin Money Flow Indicator details its calculation.
18. **On Balance Volume (OBV):** A momentum indicator that uses volume flow to predict price changes. OBV Indicator offers an explanation.
19. **Elliott Wave Theory:** A complex method of analyzing price patterns. Elliott Wave Theory Explained provides an overview.
20. **Gann Analysis:** A technical analysis approach based on geometric angles and lines. Gann Analysis is a complex topic.
21. **Candlestick Pattern Recognition:** Identifying patterns in candlestick charts to predict future price movements. Candlestick Patterns is a comprehensive resource.
22. **Volume Spread Analysis (VSA):** Analyzing price and volume to understand market sentiment. Volume Spread Analysis provides detailed information.
23. **Harmonic Patterns:** Identifying specific geometric patterns in price charts. Harmonic Patterns Trading is a complex strategy.
24. **Intermarket Analysis:** Analyzing the relationship between different markets to identify trading opportunities. Intermarket Analysis provides an overview.
25. **Sentiment Analysis:** Gauging market sentiment using various indicators. Trading Sentiment Analysis presents different approaches.
- Debugging Lua Code
Debugging Lua code in MediaWiki can be challenging. The `#invoke` syntax doesn't always provide detailed error messages. Here are some tips:
- **`mw.log()`:** Use `mw.log()` to print debugging information to the MediaWiki error logs. This is the most reliable way to see what's happening inside your Lua code.
- **Error Handling:** Use `pcall()` to catch errors and handle them gracefully.
- **Simplify:** Break down complex code into smaller, more manageable chunks.
- **Test Thoroughly:** Test your code with a variety of inputs to ensure it works correctly.
- **Consult the Scribunto Documentation:** The official Scribunto documentation ([1](https://www.mediawiki.org/wiki/Extension:Scribunto)) is an invaluable resource.
- Resources for Further Learning
- **Lua Reference Manual:** [2](https://www.lua.org/manual/5.4/)
- **Scribunto Documentation:** [3](https://www.mediawiki.org/wiki/Extension:Scribunto)
- **MediaWiki Lua Scripting Tutorial:** [4](https://www.mediawiki.org/wiki/Tutorial:Lua_scripting)
- **Lua Users Wiki:** [5](https://lua-users.org/wiki/)
- Conclusion
Lua scripting with Scribunto is a powerful tool for extending the functionality of MediaWiki. While it may seem daunting at first, with practice and a solid understanding of the fundamentals, you can create sophisticated templates and modules that enhance your wiki's capabilities. This article provides a starting point for your Lua journey. Experiment, explore, and don’t be afraid to ask for help from the MediaWiki community.
Help:Contents MediaWiki Extension:Scribunto Template:Documentation Module:Documentation Help:Lua Technical Analysis Market Trends Trading Strategy Financial Modeling Risk Management
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