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:

  1. 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!
  2. 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:

  1. Navigate to User:<your username here>/Sandbox.
  2. 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:

  1. Return to Module:Sandbox/<your username here>.
  2. Edit the line with return 'Hello!' and add your name inside the single quotes. You should end up with something like return 'Hello Lua!'.
  3. Save the page.
  4. Return to User:<your username here>/Sandbox.
  5. 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 it p.
  • function p.hello() adds a function named hello to the table. Functions can be invoked (called) by name from outside the module.
  • return 'Hello!' returns the string Hello! 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.