Lua crash course part 3
DungeonMaster00 (165)

Lua crash course part 3

This is the final tutorial in the series.

Here, we will be learning about OOP and Exception handling.

This is also where I will put the sources I used for information.

Let's begin.


OOP

Most languages have support for Object Oriented Programming.

So does Lua.

We accomplish OOP in Lua with tables, explained earlier.

How to do it:

myClass = {} -- this creates a table which can be used as a class

You can also have properties in a class like this:

myClass = {myProperty = 4, myOtherProperty = "hello"}

To add functions to classes, we don't have to put them in between the brackets. It's pretty simple actually.

function <class name>:<functions name>(<params>)
	-- funtion code
end

To access something a function from a class, do this.

<class name>:<functions name>(<params>)

To access a property from a class, do this:

<class name>.<property name>

OOP in Lua also supports inheritance.

You basically make a new class that inherits from another class.

myInheritedClass = myClass:myClassFunction()

Please help me improve the part on inheritance.

Exception handling

What are exceptions?

They are basically errors that occur while a program is running.

They will stop the program.

But we don't want that.

So we have Exception handling so that the program can still run.

Exception handling in Lua is different than most languages.

It relies on if/else statements and functions.

Step one: Put the code that could throw an exception in a function.

function codeThatMayThrowAnException()
	-- in here is the code that may throw an exception
end

Step two: Make an if statement with the pcall function.

if pcall(codeThatMayThrowAnException) then
	print("No exceptions were thrown hooray!")

Step three: Make an else for the code that runs if exceptions were thrown

if pcall(codeThatMayThrowAnException) then
	print("No exceptions were thrown hooray!")
else
	print("Sorry, an exception was thrown :(")
end

Now you have safe code!

AND SO ENDS THE THIRD AND FINAL PART OF THIS LUA CRASH COURSE! HOPE YOU ENJOYED THIS SERIES AND PLAY AROUND WITH LUA IF YOU LIKE IT! GOODBYE!

Sources

You are viewing a single comment. View All
DungeonMaster00 (165)

@ananab1221 it means that it calls a function, and detects errors. you can handle errors that way