lua-users home
lua-l archive

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


Jerome Vuarand wrote:
Shea Martin wrote:
int l_creat_player( lua_State* vm )
{
	lua_newtable( vm );

	int address = (int)&gSomePlayer;

	lua_pushstring( vm, "id" );
	lua_pushinteger( vm, address );
	lua_settable( vm, -3 );

	//Now I would like to add a function to this:

	lua_pushstring( vm, "get_mojo" );
	lua_pushcclosure( vm, l_player_get_mojo, 0 );
	lua_settable( vm, -3 );
	return 1;
}

I register the function as get_player;

My l_player_get_mojo() is like this:

int l_player_get_mojo( lua_State* vm )
{	
	lua_getfield( vm, -1, "id" );
	int address = lua_tointeger( vm, -1 );
	Player* p = (Player*)address ;
	lua_pushnumber( vm, p->GetMojo() );
	return true;
}

My script is:

player = get_player()
print( "mojo is " .. player.get_mojo() )

The code dies on getting the "id" field, as the stack does not seem to have the table on the top of the stack.

I think my problem is how I add the "member function" to the player table.

What am I missing here?

You have to use the : syntax:

player = get_player()
print( "mojo is " .. player:get_mojo() )

Then the table will be the first (and only) argument to get_mojo. You
can get it on the stack with index -1 (as you did), or better with index
1 (this makes the function more robust). Also you should use
lightuserdata to store pointers (on 64bits platforms with stock Lua and
on 32bits platform with float numbers the address cannot be safely
contained in a Lua number):


Good tip, thanks.

int l_creat_player( lua_State* vm )
{
	lua_newtable( vm );
	
	lua_pushstring( vm, "id" );
	lua_pushlightuserdata( vm, &gSomePlayer );
	lua_settable( vm, -3 );
	
	lua_pushstring( vm, "get_mojo" );
	lua_pushcclosure( vm, l_player_get_mojo, 0 );
	lua_settable( vm, -3 );
	return 1;
}

int l_player_get_mojo( lua_State* vm )
{	
	luaL_checktype(L, 1, LUA_TTABLE);
	lua_getfield( vm, 1, "id" );
	luaL_checktype(L, -1, LUA_TLIGHTUSERDATA);
	Player* p = (Player*)lua_touserdata( vm, -1 );
	lua_pushnumber( vm, p->GetMojo() );
	return true;
}


Done.  Thanks.

~S