Jump to content

Lua classes and inheritance


tjheldna
 Share

Recommended Posts

Hi All,

 

I've been a big C++ guy from the start, but I want to learn how to use lua. Most I've found pretty straight forward however I'm trying to implement classes and inheritance and have hit a wall with inheritance.

 

What I'm trying to do is have an InventoryItem class and a GunItem which inherits. Maybe I'm a little off today, don't know, I just can't seem to understand from examples from the net and I don't know if they work in LE.

 

Does anyone know of a simple tutorial for this? or have an example handy?

 

Cheers!!!!

trindieprod.png?dl=0spacer.png?dl=0steam-icon.png?dl=0twitter-icon.png?dl=0spacer.png?dl=0
Link to comment
Share on other sites

There are tons of approaches to make inheritance in Lua.

 

First of all you need to decide - "do you really need inheritance?" Or you just need similar behave for group of objects?

 

In Lua you can override properties and methods of objects "on the fly". And you don't need "polymorphism" because Lua has no types in common and you don't have to deal with type-casting.

 

The easiest way (IMO) to create similar-behave objects - to make factory-functions for each type of objects.

 


function CreateInventoryItem(picture, weight)

local obj = {}

obj.picture = picture

obj.weight = weight

 

return obj

end

 

function CreateGunItem(picture, weight, damage)

local obj = CreateInventoryItem(picture, weight)

obj.damage = damage

 

return obj

end

  • Upvote 2
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...