Module:BananasArgs

-- Sample Module demonstrating how to access arguments. -- For more about the Frame object, see http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Frame_object -- The first argument of a Lua invocation always contains the function being called. Lua modules are actually mere containers that can contain several functions each.

-- All scripts must begin by defining a variable that will hold all template-invokable functions. The variable name chosen here is "p". local p = {}

-- Add our first invokable function to the p variable. -- No arguments, used like: function p.hello_world return "Hello, world!" end

-- Add a second function to p. -- Unlike the first function, this one uses variable data that was passed in via the wiki code's "invoke" statement. -- "frame" is an object that always contains all of this data. -- frame.args[1] contains the first numbered (unnamed) argument -- ("hello" is the first #invoke parameter, but is actually the name of the function being called -- ... while "Fred" is the first argument being passed to the "hello" function). -- One argument, used like: function p.hello(frame) local name = frame.args[1] -- in this example, args[1] is the word Fred return "Hello, " .. name .. "!" -- .. name .. replace by the word Fred end

-- Two arguments, used like: function p.add(frame) local num1 = tonumber(frame.args[1]) local num2 = tonumber(frame.args[2]) return num1 + num2 end

-- Named arguments, used like: function p.count_fruit(frame) local num_bananas = frame.args.bananas local num_apples = frame.args.apples return 'I have ' .. num_bananas .. ' bananas and ' .. num_apples .. ' apples' end

-- Mixing regular args with named args and optional named args -- Used like: function p.has_fruit(frame) local name = frame.args[1] local num_bananas = frame.args.bananas local num_apples = frame.args.apples local num_cherries = frame.args.cherries local result = name .. ' has:' if num_bananas then result = result .. ' ' .. num_bananas .. ' bananas' end if num_apples then result = result .. ' ' .. num_apples .. ' apples' end if num_cherries then result = result .. ' ' .. num_cherries .. ' cherries' end return result end

-- Iterating over args, used like: function p.custom_fruit(frame) local result = 'I have:' for name, value in pairs(frame.args) do result = result .. ' ' .. value .. ' ' .. name end return result end

-- Iterating over args with separate mandatory args -- Used like: function p.custom_fruit_2(frame) local name = frame.args[1] local result = name .. ' has:' for name, value in pairs(frame.args) do		if name ~= 1 then result = result .. ' ' .. value .. ' ' .. name end end return result end

return p