lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 2-Feb-07, at 3:44 PM, Shea Martin wrote:

//I want to do something like this:
Person = {}
Person.mt = {}

function Person:new( pname )
  Person.mt.__index = Person
  return setmetatable( { name = pname }, Person.mt )
end

function Person:talk( mesg )
  print( self.name .. " says '" .. mesg .. "'." )
end

function Person:do_stuff()
  self:talk( "hello" )
end

fred = Person:new( "Fred" )
fred:do_stuff()

//I have a person 'class' I would like to partially define in my C++ program.
//I would like to the rest of it to be defined in a lua script.

You can just completely mimic the Lua implementation; that's got to be the simplest approach. See my response to the "Checking type of userdata" thread, which has some code which you shouldn't copy verbatim :) (since it's identifying classtypes in a dumb way in order to prove a point), but might help you get started. The "new" function defined there creates an empty userdata, but it could just as well have created a table. The "make" class method creates a new class and returns the metatable for that class, which can then get filled in with instance methods, either in C (using luaL_register), or in Lua. Code sample at http://primero.ricilake.net/lua/zara.c