Loading and using modules

You can load Lua modules with the require function. The require function takes one argument, which is the name of the file being loaded (without the .lua extension). The require function should return a table that can then be used as any other table.

The require function searches for the given file in several specific folder paths. These paths are stored as a string in the global variable, package.path. The default path on windows looks like this:

?;?.lua;c:windows?;/usr/local/lua/?/?.lua

This string contains multiple search paths, each separated by a semicolon (;). The ? charter gets replaced by the filename provided to the require function. So, for example, if you called require("character"), Lua would look for the following files:

  • ./character
  • ./character.lua
  • c:windowscharacter.lua
  • /usr/local/lua/character/character.lua

If multiple files exist (namely, both ./character.lua and C:windowscharacter.lua), only the first one is loaded. If you call require on the same file twice, the module is only loaded one time, avoiding duplicate work.

Let's explore how to use the character module created in the last section. First, make a new file, game.lua, in the same directory as character.lua. This file should contain the following code:

-- load the character module into a table named character
Character = require ("character")

-- Create a new hero, which is a charcter
gwen = Character:new("gwen")
gwen.strength = 10
-- Create a new enemy, also a character
orc = Character:new("orc")

-- Run game logic
gwen:attack(orc)
orc:attack(gwen)
gwen:attack(orc)

The preceding code loads the character module from character.lua into a table named Character. The loaded Character table is a class that can be used to create new objects. The code creates two character objects and runs a simulated turn-based fight.

There are two major advantages to making something like a game character class into a module. First, there is less code in game.lua and other files. Second, the Character class is now reusable. You can now use the character class in multiple files, or even multiple projects.

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

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