Log In  

I haven't played too much with lua, did some love2d a few years back, but I forgot all of it pretty much.
Right now I'm simulating classes like this;

function make_obj()
    e = {x = 10, y=10, sprite=1

        draw=function()
            --draw 
        end,

        update=function()

        end
    }
end

I was wondering if some form of inherritance is possible, something like this;

function make_animated_obj()
    e = make_obj(); --base class values
    e.animspeed = 10
    e.sprites = {1,2,3,4}

    e.draw=function()
        --override completely with new rendering for animaions  
    end,

        update=function()
            base.update() --csll original e's update function first
            --do additional stuff
        end
    }
end

Or perhaps there is an entirely different way from how I'm simulating classes in the first place, I'd also like to see that.
Thanks!

P#24935 2016-07-08 21:15 ( Edited 2016-07-11 13:28)

You should take a look at the docs on lua.org and read up on metatables. It's a sort of roundabout way to simulate things like classes and virtual function tables.

A metatable lets you override builtin methods like add(), but you can also add an entry to the metatable ("index") that references a second table with your own standard methods for anything with that metatable. It's the equivalent of a virtual function table. By deep-copying and modifying a base class's __index table, you can sort of derive and override and such.

P#24947 2016-07-09 00:01 ( Edited 2016-07-09 04:02)

Also note that Lua has two ways of calling 'methods':

object.method1()

and

object:method2()

The first is basically like a C++ static function, with no 'self' available. The second is syntactic sugar for having a 'self' param auto-passed. You can actually call object:method2() by writing ojbect.method2(self) (with a dot instead of a colon) and it's identical under the hood.

P#24948 2016-07-09 00:08 ( Edited 2016-07-09 04:08)

Description and complete example of inheritance in Pico-8: http://pico-8.wikia.com/wiki/Setmetatable

P#24951 2016-07-09 01:39 ( Edited 2016-07-09 05:39)

I thought I had read somewhere that Setmetatable was not available. Guess I read incorrectly, doh.
Thanks for the replies, I can certainly work with this :D

P#24993 2016-07-09 16:06 ( Edited 2016-07-09 20:06)

setmetatable() is available since 0.1.6.

Interestingly enough, getmetatable() is not. Rare are the cases where you need it, but if you really do, I created an implementation of the function (alongside multiple other missing Lua functions in pico8).

P#25087 2016-07-11 09:28 ( Edited 2016-07-11 13:28)

[Please log in to post a comment]