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!
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.
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.
Description and complete example of inheritance in Pico-8: http://pico-8.wikia.com/wiki/Setmetatable
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).
[Please log in to post a comment]