lua-users home
lua-l archive

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


Here's an example how I enabled texture handling in GLFW:


static int glfw_GLFWImageGetSize( lua_State *L )
{
	GLFWimage *img = (GLFWimage*)luaL_checkudata(L,1,"GLFWimage");
	lua_pushnumber(L,img->Width);
	lua_pushnumber(L,img->Height);
	lua_pushnumber(L,img->BytesPerPixel);
	return 3;
}

static void pushGLFWImage_metatable( lua_State *L )
{
	if (luaL_newmetatable(L,"GLFWimage")) {
		lua_pushcfunction(L,glfw_FreeImage);
		lua_setfield(L,-2,"__gc");

		lua_newtable(L);
		lua_pushcfunction(L,glfw_LoadTextureImage2D);
		lua_setfield(L,-2,"load");
		lua_pushcfunction(L,glfw_GLFWImageGetSize);
		lua_setfield(L,-2,"size");
		lua_pushcfunction(L,glfw_GLFWImageGetData);
		lua_setfield(L,-2,"data");

		lua_setfield(L,-2,"__index");
	}
}
static int glfw_ReadImage( lua_State *L )
{
	GLFWimage *img;
	img = (GLFWimage*)lua_newuserdata(L,sizeof(GLFWimage));
	if (glfwReadImage(luaL_checkstring(L,1),img,luaL_checkint(L,2)) == GL_FALSE) {
		lua_pushnil(L);
		return 1;
	}
	pushGLFWImage_metatable(L);
	lua_setmetatable(L,-2);
    return 1;
}



You'll notice 3 functions in this example:
- static int glfw_ReadImage( lua_State *L )
- static void pushGLFWImage_metatable( lua_State *L )
- static int glfw_GLFWImageGetSize( lua_State *L )

glfw_ReadImage constructs new userdata objects by pushing these on the
stack. It associates them with a metatable which handles OO-like
behavior, by pushing it on the stack using the pushGLFWImage_metatable
function. That function initializes the metatable if it does not yet
exist. It uses the __gc key of the metatable to call the free function
of glfw to take care of the image structure if it is no longer needed.
The glfw_GLFWImageGetSize method is an example for a method function.
It expects the first argument to be an userdata object with the
GLFWImage metatable. Then it's pushing the requested information from
that struct obtained from the userdata on the stack and returns them.
Last but not least, some Lua code how it's used:

tiles = glfw.ReadImage("tex/tiles.tga",0)
print("tex size: ",tiles:size())

Hope this clearifies it a bit on how to integrate OO methods through
the Lua API.

Cheers,
Eike


2010/3/7  <mailing_lists@imagine-programming.com>:
> A good day everyone,
>
> I was wondering, I know how to push a function in lua, but now I'd like to
> know how
> to register a method in back-end lua. I've been writing lot's of luascripts
> to extend
> existing functions, but in a L-OOP way, because I don't know how to do this
> from
> the backend.
>
> Thanks!
>
> Sincerely,
> Bas Groothedde.
> Excuse me for my English and/or explanation of my problem.