lua-users home
lua-l archive

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


That makes the metatable for the monster. (Roughly comparable to C++ class.)

Then three lines to set the metatable itself as its __index, so those methods can be used.

When a monster is created, it gets that metatable. That's how it can rawr.

Sent from my new BlackBerry Z10

From: TheGreat Guru
Sent: Saturday, February 23, 2013 8:18 AM
To: lua-l@lists.lua.org
Reply To: Lua mailing list
Subject: Question

Hello ! I am kinda new to lua and programming in general . I have a
question about one part of the following code :

//------------------------------------------------------------------------------------
class Monster {

public:

Monster (int h) {
hp = h;
}

~Monster () {
// ...
}

void rawr () {
std::cout << "Gonna eat you !" << std::endl;
}

int hp;
};
//------------------------------------------------------------------------------------
int monster_create (lua_State * ls)
{
int a = lua_tointeger(ls,-1);
Monster * monster = new (lua_newuserdata(ls, sizeof(Monster))) Monster (a);
luaL_getmetatable(ls, "MetaMonster");
lua_setmetatable(ls, -2);

return 1;
}
//------------------------------------------------------------------------------------
int monster_rawr (lua_State * ls)
{
luaL_checktype(ls, -1, LUA_TUSERDATA);
Monster * monster = reinterpret_cast<Monster*>(lua_touserdata(ls, 1));
monster->rawr();

return 0;
}
//------------------------------------------------------------------------------------
static const luaL_reg Monster_funcs[] =
{
{"create", monster_create},
{0, 0}
};
//------------------------------------------------------------------------------------
static const luaL_reg Monster_methods[] =
{
{"rawr", monster_rawr},
{"greet", monster_greet},
{"jump", monster_jump},
{0, 0}
};
//------------------------------------------------------------------------------------
//The following is in main.cpp !

lua_State* ls = lua_open (ls);
luaL_openlibs (ls);

luaL_newmetatable(ls, "MetaMonster");
lua_pushstring(ls, "__index");
lua_pushvalue(ls, -2);

lua_settable(ls, -3);

luaL_openlib(ls, 0, Monster_methods, 0);
luaL_openlib(ls, "Monster", Monster_funcs, 0);

luaL_dofile (ls,"new.lua");
//------------------------------------------------------------------------------------

The following code runs perfectly fine ! But i have one question :
Can someone explain me the following lines:

luaL_newmetatable(ls, "MetaMonster");
lua_pushstring(ls, "__index");
lua_pushvalue(ls, -2);

lua_settable(ls, -3);

I mean why they are used ? What they achieve ? Why they are needed ?!

I am obvioulsy new to this and the code is NOT mine (dah !) ....

Thank you all in advance !!!