Adventures in Lua: Part 2 - OOP

Danni's picture

So I read a small portion of "Programming in Lua", which starts out easy enough and then becomes more and more bullshit the further you read into it. So I started skipping chapters, and then eventually decided to look elsewhere for information on OOP in Lua.

They recommended the use of metatables and goofy complicated things just to get stuff like inheritance and encapsulation working. Not my method! Relevant code is here. Any experienced Lua programmers are welcome to berate me on how my method is "too simple" and "doesn't use metatables" and stuff like that.

Next, I shall make a basic game in Love2D with this OOP method. I already have a framework in the works.

Comments

SpindleyQ's picture

Not a fan of the colon

Not a fan of the colon syntax, eh?

Your method is fine (in that it works and will be reasonably efficient), but requiring boilerplate that you have to go back and fix up anytime that you make changes to the base class will probably bite you at some point.

Danni's picture

Here's a version with less

Here's a version with less boilerplate code. You define the interface table and then call inherit() with the table and a new instance of the superclass you want. It's a bit weird since you have to call the function after, not before, but it gets the job done.

Danni's picture

So I eventually decided to

So I eventually decided to scrap this because it had very, very poor performance. I'm right now using the method suggested in "Programming in Lua", which means I eschew class member privacy in the name of better performance and using more widely accepted syntax. I don't think Lua is even much of a stickler about privacy...

jonbro's picture

I would just use an off the

I would just use an off the shelf one instead of rolling you own. You might want to take a look at "middleclass" which was made by one of the love2d forum members. I just use the one on the lua wiki: http://lua-users.org/wiki/SimpleLuaClasses