lua-users home
lua-l archive

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


> Hello everyone!
> 
> --------------------------------------
> int BITMAP_load(lua_State *L)
> {
> 	const char *file = luaL_optstring(L, 1, "\0");
> 	
> 	BITMAP *bmp = (BITMAP*)lua_newuserdata(L, sizeof(BITMAP));
> 	BITMAP *bmp2 = load_bitmap(file, 0);
> 	
> 	if (bmp2 == NULL) error("Cannot load image!");
> 	
> 	memcpy(bmp, bmp2, sizeof(BITMAP));
> 	
> 	luaL_getmetatable(L, "Bitmap");
> 	lua_setmetatable(L, -2);
> 	
> 	destroy_bitmap(bmp2);
> 	
> 	return 1;
> }
> --------------------------------------
> 
> Am I doing it right? Doesn't seem like it. Here's my GDB output:
> (hope it's clear enough, I stripped some print statements)

Hello there,

memcpy a BITMAP? Arrrgh!!! Shawn would kill you for a stunt like that :-)

Your problem is not a Lua issue its more an Allegro issue. An allegro BITMAP is a complex structure with pointers and stuff, and you cannot just copy it like that.

A better solution is this:

int BITMAP_load(lua_State *L)
{
  const char *file = luaL_optstring(L, 1, "\0");
  BITMAP**bmp = (BITMAP**)lua_newuserdata(L, sizeof(BITMAP*));
  *bmp = load_bitmap(file, 0);
  if (*bmp == NULL) error("Cannot load image!");
  luaL_getmetatable(L, "Bitmap");
  lua_setmetatable(L, -2);
  return 1;
}

This way, you just pass the BITMAP into lua and let it manage it.
You will need to have a metatable with a __gc method to do the destroy_bitmap() as well. But thats the idea.

However: and even better idea is to seriously consider either using an existing wrapper, or using a tool to generate the wrappers for you.
You mentioned in one of the other posts that you have some other game engine components which need to be wrappered.  That doesn't stop you from using the ready written code & extending it.

<blatant plug>I use SWIG which is an tool for writing wrappers. Its not hard to wrappers most of Allegro. And it will probably easily be able to wrapper your engine at the same time</blatant plug>

Regards,
Mark