Creating a module

A module is just a normal Lua table; a module file is a Lua file which returns a table. For us, this means returning an anonymous table. We are going to create a new file, character.lua, and declare a character class in this file. The definition of the character class is as follows:

-- It's important that the table retuned be local!
local character = {}

character.health = 20
character.strength = 5
character.name = ""

character.new = function (self, object)
object = object or {} -- Use provided table, or create new one
local provided = ""

if type(object) == "string" then
provided = object
object = {}
end

setmetatable(object, self) -- Assign meta table
self.__index = self

if provided ~= "" then
object.name = provided
end

return object
end

character.attack = function(self, other)
print (self.name .. " attacks " .. other.name)
other.health = other.health - self.strength
if other.health < 1 then
print (" " .. other.name .. " is dead")
else
print (" " .. other.name .. " has " .. other.health .. " health left")
end
end

return character

The previous code creates a table local to the file and returns it. This table has five variables; three of them are values and two are functions. This module represents character class, which has a health, a name, and some strength. The attack function will decrease the health of whatever character is being attacked, and print out some information.

The constructor is similar to that seen in previous chapters, except it does a type check on the second argument. This allows the constructor to clone a character object, or to provide a name as a constructor argument.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.255.87