Programming without class()

I still dont understand the “class()” and “self” thing. I stay in the Main file. But everything works, and I have no Problems with interacting objects. But do i have any Restrictions?

Classes are abstract data types. This is a fancy way of saying that you can take a thing, a circle for example, and generalize it. All circles have common attributes such as radius, diameter, area, etc. You could create a “circle class” to capture and encapsulate this idea into an object that contains both data and methods of acting on the data. A more general object would be a “shape class” where a circle is just one type of shape.

As far as restrictions go there is really nothing that you can’t do without classes. They just make life easier and code becomes much more readable when they are used. I hope this is helpful to you in some small way.

A class is a way to bundle data and methods together. This allows you to create an “object”, a thing in memory that knows about itself.

The simple example is if I made an “Animal” object, I could make one called “cow” and one called “cat”, both with a “speak()” method. When I initialize the object, I can tell it what a cow says, and what a cat says, and later I can simply say “speak” and get out the right thing for that current object - cow.speak() would go “moo”, while cat.speak() would go “meow”. You can do this without objects - but it’s harder to set up and maintain, and it’s a lot more likely what you do will conflict with other packages.

“self”, in the context of Classes and objects, is a variable that refers to the current object. So, in the “Animal” object (or class), I might have:

cow = Animal("Moo!")
cat = Animal("Meow")

barnyard = { cow, cat }

for k,v in pairs(barnyard) do
   print(v.speak())
end

Animal = class()

function Animal:init(s)
    self.sound = s
end

function speak() 
   print(self.sound)
end

The line that starts with “Animal” is the start of the class. The stuff before it is an example of usage.

When I call cow.speak(), it looks for “self.sound” - we call this an “instance variable”, a variable that’s part of that particular instance of the object. When I created “cow”, I passed the contents of the “sound” variable, so it knew what to do later on when I call speak().

Why is this useful? Well - for our simple example, you could put cow and cat into a table, and iterate thru the table calling speak() - and you’ll get out whatever is appropriate for each object.

If you go look at the classes in the example programs, you’ll see objects/classes used in lots of different ways - use those as a guide to show you the kinds of things you might want to do.

(I’ve moved this out of the “Members Only” category since that can’t be seen by people browsing the forum and there’s no reason for this to be a private discussion. That category appears first on the list in the categories so if you don’t actually select a category for your discussion it ends up there automatically.)