Scripting a Class

To create a pure Lua class, you need to start out with a table. CustomClass = {} Then you need to use the CreateClass function. All this function does is set up your class in the global table, as well as creating a helper function to create instances of the class. CreateClass("CustomClass", CustomClass) All of the member functions for this class MUST go in between these two lines of code. Any member functions declared outside of these will not work.

Here is an example of creating an update function for our class: function CustomClass:Update print("I am updating!") end A few notes on this declaration, first note the use of the ":" when declaring the function. Similar to calling a member function, the colon specifies that this functions declaration implies a "self" variable that can be used inside of the function to access its local variables.

To create local variables inside of the class, you must first create a constructor for the class. The constructor is just a function with the same name of the class.

Here is an example of a constructor: function CustomClass::CustomClass self.var1 = 1 self.var2 = "I am a string!" end Like every other function, the constructor can take arguments which can be specified when creating an instance of the class.

With this constructor for our class, we can now modify the update function to print these variables: function CustomClass:Update print("I am updating!") print("I also have 2 variables! " .. self.var1 .. " and " .. self.var2 .. ".") end Finally, to create an instance of the class simply call a function with the name of the class: local customInstance = CustomClass customInstance:Update Here is the complete code for the class: CustomClass = {} function CustomClass:Update print("I am updating!") print("I also have 2 variables! " .. self.var1 .. " and " .. self.var2 .. ".") end function CustomClass::CustomClass self.var1 = 1 self.var2 = "I am a string!" end CreateClass("CustomClass", CustomClass) --Somewhere else-- local customInstance = CustomClass customInstance:Update That's all for creating a class! See Creating the ActionList System for more details.