Jump to content

Module:Example

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Pppery (talk | contribs) at 23:30, 21 February 2020 (Example module merge step two: First function of Module:BananasArgs (called "Hello" at the source), originally written by User:Dcoetzee (comments are my own addition)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

local p = {};     --All lua modules on Wikipedia must begin by defining a variable 
                    --that will hold their externally accessible functions.
                    --Such variables can have whatever name you want and may 
                    --also contain various data as well as functions.

p.hello = function( frame )     --Add a function to "my_object".  
                                        --Such functions are callable in Wikipedia
                                        --via the #invoke command.
                                        --"frame" will contain the data that Wikipedia
                                        --sends this function when it runs. 
    
    local str = "Hello World!"  --Declare a local variable and set it equal to
                                --"Hello World!".  
    
    return str    --This tells us to quit this function and send the information in
                  --"str" back to Wikipedia.
    
end  -- end of the function "hello"
function p.hello_to(frame)		-- Add another function
	local name = frame.args[1]  -- to access arguments passed to a module by
							    -- the corresponding template, use `frame.args`
							    -- `frame.args[1]` refers to the first unnamed parameter
							    -- given to the module
	return "Hello, " .. name .. "!"  -- `..` concatenates strings. This will return a customized
									 -- greeting depending on the name given, such as "Hello, Fred!"
end
return p    --All modules end by returning the variable containing its
                    --functions to Wikipedia.

-- Now we can use this module by calling {{#invoke: HelloWorld | hello }}.
-- or {{#invoke: HelloWorld | hello_to | foo }}
-- Note that the first part of the invoke is the name of the Module's wikipage,
-- and the second part is the name of one of the functions attached to the 
-- variable that you returned.

-- The "print" function is not allowed in Wikipedia.  All output is accomplished
-- via strings "returned" to Wikipedia.