Game Development Reference
In-Depth Information
function newAnimal(name)
local animal = {
name = "unknown",
says = "pffft",
position = {x = 0,y = 0},
}
animal.name = name
if name=="cat" then
animal.says = "meow"
elseif name=="dog" then
animal.says = "bow wow"
elseif name=="mouse" then
animal.says = "squeak"
end
function animal:speak()
print(animal.says)
end
function animal:move(speed)
animal.position.x = animal.position.x+speed
end
return animal
end
Now we can create a new instance of an animal by simply calling
cat_01 = animal.new("cat")
cat_01:speak()
This is perfectly fine as an example that creates a new object every time it is invoked. However, this
is also how many beginners would code—note that in the functions, while we are passing the object
via self , we are not using it, and we are still referencing it by the fixed animal table that we created.
This can cause a bit of grief later on if it's not checked right at the start. The way to avoid this being
a problem in the future is to replace the namespace with the object referenced as self instead.
The modified code would look like the following:
function newAnimal(name)
local animal = {
name = "unknown",
says = "pffft",
position = {x = 0,y = 0},
}
animal.name = name
if name=="cat" then
animal.says = "meow"
elseif name=="dog" then
animal.says = "bow wow"
elseif name=="mouse" then
animal.says = "squeak"
end
Search WWH ::




Custom Search