I need help on making and using classes.

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
PixelHero
Prole
Posts: 45
Joined: Sat Apr 16, 2022 3:16 am

I need help on making and using classes.

Post by PixelHero »

Hello, I'm making a platformer game, and I need help implementing classes. I read Sheepolution's tutorial, so now I somewhat know how to make a class, but I don't know how to use it after I make it, aside from making subclasses. :? Can anyone help?
Dragons are great.
User avatar
VeneratedVulture
Prole
Posts: 1
Joined: Tue Jan 17, 2023 10:24 pm

Re: I need help on making and using classes.

Post by VeneratedVulture »

So to use classes you first need to make a class:

Code: Select all

table = {} 
table.value = 10
Then to use this class you will want to use a function like this:

Code: Select all

function table:function()
   table.value = 20 
end
Then after making the function you will need to call the function from a callback function i.e. love.update, love.load, etc.

Code: Select all

function love.load()
   table:function() -- sets table.value from 10 to 20
   print(table.value) -- prints 20
end
Last edited by VeneratedVulture on Mon Feb 20, 2023 9:06 pm, edited 2 times in total.
User avatar
zorg
Party member
Posts: 3465
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: I need help on making and using classes.

Post by zorg »

So, to use a class, you first need to make one; either using a class library, or just build your own:

Code: Select all

local class = {}
local mtClass = {__index = class}

-- set some member value
class.val = 5

-- have a method (could also be written function class.foo(self) or function class:foo() as well, it doesn't matter)
class.foo = function(self)
  print(class.val, self.val)
end

-- create an instance of a class
local function new()
  local instance = {}
  instance.val = 4
  instance.setmetatable(instance, mtClass)
  return instance
end

return class -- if class is in its own lua file, probably should be
Then after making your class, you use the constructor to create instances and do stuff with them:

Code: Select all

local myclass = require 'class' -- if the class is in a file called class.lua in the same place this file is.

local myinstance = myclass()
myinstance:foo() -- or myinstance.foo(myinstance), same thing; will print 5,4.



By the way, don't call your class neither "class" because it's too generic, but especially not "table" because that is actually used by lua, so you don't want to redefine that variable.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
RNavega
Party member
Posts: 355
Joined: Sun Aug 16, 2020 1:28 pm

Re: I need help on making and using classes.

Post by RNavega »

It's not really classes since Lua doesn't have such a feature, but it's class-like behavior -- specifically the part about 'inheritance' and 'interface'.

What you're doing is giving a template for your tables.

In Lua there's two ways to do that:
  1. Using the metatable feature:
    1. Make a table that will be your template, giving it keys for all the functions that you want other tables to "inherit".
    2. Store that template table in the __index key of a table that will be used as the metatable that all inheriting tables will use.
    3. To create new table following that template (an "instance"), set the metatable of the new table to the one that has that __index key pointing to the template table. You can use the template table itself as the metatable, if you add the __index key to it with the value as itself, like...
      TemplateTable.__index = TemplateTable
      setmetatable(myInstance, TemplateTable)
  2. Manually storing functions into the new table that must follow the template, like going...
    t = {}
    t.function1 = function1
    t.function2 = function2
    (Preferably using a function, like a factory function, where it takes in a preexisting table or creates a new table, then stores all the needed functions into that table and returns it. So to get a new instance you call that function).
Both methods give a different result that can be used in the same way: all instance tables will come preset with keys to functions from their templates, and you can override any functions stored in those keys with custom ones that only the instance table knows about. You can do the same with template tables too, for sub-templates.
Last edited by RNavega on Thu Mar 30, 2023 9:46 pm, edited 1 time in total.
User avatar
darkfrei
Party member
Posts: 1197
Joined: Sat Feb 08, 2020 11:09 pm

Re: I need help on making and using classes.

Post by darkfrei »

From chatGPT(not tested):
Here is an example implementation of a clickable object library in Lua using metatables and methods:

Code: Select all

-- define a clickable object metatable
local ClickableObject = {}
ClickableObject.__index = ClickableObject

-- constructor
function ClickableObject:new(x, y, width, height, callback)
    local obj = {
        x = x,
        y = y,
        width = width,
        height = height,
        callback = callback
    }
    setmetatable(obj, ClickableObject)
    return obj
end

-- check if a point is inside the clickable object
function ClickableObject:contains(x, y)
    return x >= self.x and x <= self.x + self.width and y >= self.y and y <= self.y + self.height
end

-- handle click events on the clickable object
function ClickableObject:onClick(x, y)
    if self:contains(x, y) and self.callback then
        self.callback()
    end
end

-- create a new clickable object and add it to the objects table
function clickable(x, y, width, height, callback)
    local obj = ClickableObject:new(x, y, width, height, callback)
    table.insert(objects, obj)
    return obj
end

-- handle mouse click events by checking if any of the clickable objects were clicked
function love.mousepressed(x, y, button)
    if button == 1 then -- left mouse button
        for _, obj in ipairs(objects) do
            obj:onClick(x, y)
        end
    end
end
To use this library, you can create a new clickable object by calling the clickable function, passing in the x and y position, width and height, and a callback function that will be executed when the object is clicked. For example:

Code: Select all

function love.load()
    objects = {}

    -- create a new clickable object
    clickable(100, 100, 50, 50, function()
        -- code to execute when the object is clicked
        print("Object clicked!")
    end)
end
In this example, a new clickable object is created at position (100, 100) with a width and height of 50 pixels, and a callback function that prints a message to the console when the object is clicked.

When the left mouse button is clicked, the love.mousepressed function is called, which in turn calls the onClick method on each of the clickable objects in the objects table. If the mouse click is inside the bounds of a clickable object, the callback function for that object will be executed.
:awesome: in Lua we Löve
:awesome: Platformer Guide
:awesome: freebies
User avatar
slime
Solid Snayke
Posts: 3162
Joined: Mon Aug 23, 2010 6:45 am
Location: Nova Scotia, Canada
Contact:

Re: I need help on making and using classes.

Post by slime »

darkfrei wrote: Wed Feb 22, 2023 1:35 pm From chatGPT(not tested):
Please don't copy/paste replies from outside sources that you haven't vetted. If you don't have a good answer to a question yourself you can leave it to other people to answer. Doing the equivalent of googling the question and posting a stackoverflow result without looking it over isn't helpful (and can be actively misleading) in the long run.
RNavega
Party member
Posts: 355
Joined: Sun Aug 16, 2020 1:28 pm

Re: I need help on making and using classes.

Post by RNavega »

RNavega wrote: Wed Feb 22, 2023 12:03 am B. Manually storing functions into the new table that must follow the template
Re-reading this, I just noticed that in both cases you are "directly storing functions in the keys of a table".
The difference is, in one case you do it once on a table that will be reused as the metatable to other tables, and in the other case you're filling in the other tables themselves with a set of functions / initial values for variables.

If all of this setup is hidden inside a helper function, the user of these tables won't know the difference.
I think people just prefer the metatable method because it's what "emotionally" feels the most similar to actual OOP class inheritance. I don't know why but it does feel cleaner.
User avatar
PixelHero
Prole
Posts: 45
Joined: Sat Apr 16, 2022 3:16 am

Re: I need help on making and using classes.

Post by PixelHero »

Sorry, just got back to this. Probably would have helped if I had told you that I am using the library 'classic' https://github.com/rxi/classic.
Dragons are great.
RNavega
Party member
Posts: 355
Joined: Sun Aug 16, 2020 1:28 pm

Re: I need help on making and using classes.

Post by RNavega »

Going back to your original question, "how do I use it (classes made w/ classic)", the main Github page has one example of how to create an object (an "instance") from a class: https://github.com/rxi/classic#creating-a-new-object

If that isn't enough for you then that means you don't know what Object-Oriented Programming (OOP) is, and need a crash course.

After looking for a few minutes, the best free resources seem to be these: Everyone has a different taste and learning style, so you at least have the keywords needed to look for other resources.
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests