lua-users home
lua-l archive

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


//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.

//this function is registered as GetNewPerson( name )
static int l_newPerson( lua_State* vm )
{
  luaL_checktype( vm, -1, LUA_TSTRING );
  std::string name = lua_tostring( vm, -1 );
  lua_pop( vm, 1 );

  lua_newtable( vm );

  lua_pushstring( vm, "Person:name" );
  lua_string( vm, name.c_str() );
  lua_settable( vm, -3 );

  lua_pushstring( vm, "Person:talk" );
  lua_pushclosure( vm, l_person_talk, 0 );
  lua_settable( vm, -3 );

  luaL_newmetatable( vm, "Person.mt" );

  lua_pushstring( vm, "__index" );
  lua_pushstring( vm, "Person" );
  lua_settable( vm, -3 );

  return 1;
}

//now I would like the script to define Person:do_stuff.
//Thus my script would be shortened to:

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

fred = GetNewPerson( "Fred" )
fred:do_stuff()


I hope this makes sense...
Thanks,

~S