Module:Example

--- Basic Lua module example. -- <> -- -- Each module is identified with its Self table, so its documentation can be here. -- -- The structure is: -- --  1. this top comment, with category --  2. imports (_ for Core, etc.) --  3. Self table, think class or object --  4. private and public definitions --  5. tests, also can be in a different module --  6. returning Self -- -- : --  * implement and explain inheritance (hide details in Module:Core), other OOP as well -- -- Test with -- --  luafmt -l 120 -i 2 -w replace Example.lua && luacheck Example.lua && luatest Example.lua --

local _ = require("Module:Core")

local Self = { -- some keys and values "1", -- [1] = "1" true, -- [2] = true foo = "foo", -- ["foo"] = "foo" ["1 2"] = 12, -- private field, using _ as a convention _format = "${one}, ${two}, ${foo}, ${one_two}" }

--- Returns a string representation of the module table. -- Using string concatenation, only should be used for 2-3 strings. function Self:show return self[1] .. ", " .. tostring(self[2]) .. ", " .. self.foo .. ", " .. self["1 2"] end

--- Using table.concat, should be used for large number of string chunks. function Self:show2 return table.concat({self[1], tostring(self[2]), self.foo, self["1 2"]}, ", ") end

--- Using string.format. Can be used for 1-2 strings. function Self:show3 return string.format("%s, %s, %s, %s", self[1], tostring(self[2]), self.foo, self["1 2"]) end

--- Using _.format. This should be preferred for string templates. -- A private method, defaulting for format parameter. function Self:_show4(format) format = format or "${one}, ${two}, ${foo}, ${one_two}" return _.format { format, one = self[1], two = tostring(self[2]), foo = self.foo, one_two = self["1 2"] } end

--- Using _.format and self._format. -- Another public method, using private method. function Self:show4 return self:_show4(self._format) end

_.test( Self,  "Example: testing public methods...",  function(self)    local result = "1, true, foo, 12"    assert(self:show == result)    assert(self:show2 == result)    assert(self:show3 == result)    assert(self:show4 == result)  end )

-- p.test

return Self