lua-users home
lua-l archive

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


Tomas Guisasola Gorham wrote:
	Hi Shea

On Thu, 1 Feb 2007, 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.
	Don't you have to call the function with the argument?
Something like: player:get_mojo() ?  I think it should be better
to check for the argument.  For that, see the luaL_check* functions.
Or better, you should consider using a full userdata instead of a
table.  You could set its metatable to store the function and use
the __index to retrieve it.  Take a look at Roberto's book!

	Regards,
		Tomás


Yeah, I figured out the player:get_mojo() part after I had posted.

I will look at the userdata method. Who is Roberto, and where is his book? Is it online.

~S