How to extend the mesh class

I don’t know if I’m being a total noob here or what, but here’s what I want to do.
The current mesh library is great but it can be a little long winded to setup, adding vertices, colour information etc.
So what I wanted to do was create a library of mesh “helper” functions - like the mesh:addRect but more suited to what I want to do in terms of adding a quad or a poly and being able to set all the individual vertex colours etc.

Anyway as a test in main I did this

function mesh:addTri(x1,y1,x2,y2,x3,y3)
     -- Put code to add a triangle here
end

function mesh:addQuad(x1,y1,x2,y2,x3,y3,x4,y4)
     -- Put code to add a quad here
end

Hoping that this should add the function addQuad to the main “mesh” object / class / table so it would then be available to all instances of “mesh”, but instead I get an error “attempt to index global ‘mesh’ (a function value)”, I’m not sure what I’ve done wrong or if I have to do anything extra with metatables to get this to work.

Any advice greatly received. :slight_smile:

As mesh is userdata and not a standard class you can’t add functions directly, you need to add them to its metatable:

local mt = getmetatable(mesh())

mt["addTri"] = function (self,x1,y1,x2,y2,x3,y3)
  -- your code here
end

@Andrew_Stacey - Dang that was fast :slight_smile: , I knew it’d be possible but wasn’t sure how the metatable stuff in lua works.

Thanks again :slight_smile:

@TechDojo I freely admit that I learnt about it from someone else here (don’t remember who). I use it in my quaternion class to make it possible for a quaternion to act on a vec3 using notation like v^q.