Library With Userdata Example

lua-users home
wiki

Description

This example is similar to UserDataExample and UserDataWithPointerExample, except it is updated for the Lua 5.2 API.

Lua input file

function foo()
    local obj = MyLib.MakeObj()
    obj:method()
end

foo()
        

C code


#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

const static char *Obj_typename = "ObjTypename";

void check_Obj(lua_State *L, int i){
	luaL_checkudata(L, i, Obj_typename);
}

int MyLib_MakeObj(lua_State *L){
	printf("In MyLib_MakeObj\n");
	lua_newuserdata(L, sizeof(int*));
	luaL_setmetatable(L, Obj_typename);
	return 1;
}
int Obj__gc(lua_State *L){
	printf("In Obj__gc\n");
	return 0;
}
int Obj_method(lua_State *L){
	printf("In Obj_method\n");
	check_Obj(L, 1);
	return 0;
}

int luaopen_MyLib(lua_State *L){
	static const luaL_Reg Obj_lib[] = {
		{ "method", &Obj_method },
		{ NULL, NULL }
	};
	
	static const luaL_Reg MyLib_lib[] = {
		{ "MakeObj", &MyLib_MakeObj },
		{ NULL, NULL }
	};
	
	luaL_newlib(L, MyLib_lib);

	// Stack: MyLib
	luaL_newmetatable(L, Obj_typename); // Stack: MyLib meta
	luaL_newlib(L, Obj_lib);
	lua_setfield(L, -2, "__index"); // Stack: MyLib meta
	
	lua_pushstring(L, "__gc");
	lua_pushcfunction(L, Obj__gc); // Stack: MyLib meta "__gc" fptr
	lua_settable(L, -3); // Stack: MyLib meta
	lua_pop(L, 1); // Stack: MyLib
	
	return 1;
}

int main(int argc, char *argv[]){
	int iarg;
	lua_State *L = luaL_newstate();
	luaL_openlibs(L);
	
	luaL_requiref(L, "MyLib", &luaopen_MyLib, 1);
	lua_pop(L, 1); // requiref leaves the library table on the stack

	printf(" stack top: %d\n", lua_gettop(L));
	for(iarg = 1; iarg < argc; ++iarg){
		int s = luaL_loadfile(L, argv[iarg]);

		if(s != 0){
			fprintf(stderr, "Could not load: %s\n", argv[iarg]);
			continue;
		}
		s = lua_pcall(L, 0, 0, 0);
		if(s != 0){
			fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
			lua_pop(L, 1);
		}
	}
	lua_close(L);
	return 0;
}
        

Compiling the code

gcc -I/usr/include/lua5.2 ex.c -llua5.2 -o lualibex
        

Expected output

 stack top: 0
In MyLib_MakeObj
In Obj_method
In Obj__gc
        

RecentChanges · preferences
edit · history
Last edited December 17, 2012 12:49 am GMT (diff)