Help:Lua/My first Lua script
From Bulbapedia, the community-driven Pokémon encyclopedia.
Jump to navigationJump to search
This page will walk you through creating a Lua script, and including it on a wiki page.
Create the script
To create the script:
- Navigate to Module:Sandbox/<your username here>. This is your sandbox in the Module namespace, and you are free to experiment with it how you wish!
- Clear any existing code from the page. Add the following code and save the page:
local p = {} function p.hello() return 'Hello!' end return p
Test the script
To test the script:
- Navigate to User:<your username here>/Sandbox.
- Add the following code (replacing
<your username here>
with your username) and save the page:
{{#invoke:Sandbox/<your username here>|hello}}
The result should be:
- Hello!
Edit the script
To edit the script:
- Return to Module:Sandbox/<your username here>.
- Edit the line with
return 'Hello!'
and add your name inside the single quotes. You should end up with something likereturn 'Hello Lua!'
. - Save the page.
- Return to User:<your username here>/Sandbox.
- Refresh the page to see your name returned from the script.
The result should be something similar to:
- Hello Lua!
Understand your script
Let’s look at the components of the script:
local p = {}
creates a local table/array for your script and names itp
.function p.hello()
adds a function namedhello
to the table. Functions can be invoked (called) by name from outside the module.return 'Hello!'
returns the stringHello!
when the function is invoked (called).end
ends the function.return p
returns the script table to whatever process has loaded this Lua module.
The code that runs the script includes:
#invoke:
invokes (calls) a Lua module, and loads something.Sandbox/<your username here>
specifies the name of the module to be loaded.hello
specifies the name of the function inside the module that is to be invoked (called).
Conclusion
Congratulations! You've now created, tested, edited, and understood your first Lua script.