Skip to content

Instantly share code, notes, and snippets.

@tacigar
Last active November 5, 2017 03:56
Show Gist options
  • Save tacigar/b622d07921af21179af774b95f497813 to your computer and use it in GitHub Desktop.
Save tacigar/b622d07921af21179af774b95f497813 to your computer and use it in GitHub Desktop.
Lua C APIを触ってみた.
#include <lua5.2/lua.h>
#include <lua5.2/lualib.h>
#include <lua5.2/lauxlib.h>
#define POINT2D_CLASS "Point2D"
typedef struct point2d { int x; int y; } point2d;
static void create_point2d(lua_State *L, int x, int y) {
point2d* pnt = (point2d *)lua_newuserdata(L, sizeof(point2d));
luaL_getmetatable(L, POINT2D_CLASS);
lua_setmetatable(L, -2);
pnt->x = x;
pnt->y = y;
}
static int point2d_constructor(lua_State *L) {
int x = luaL_checkinteger(L, 1);
int y = luaL_checkinteger(L, 2);
create_point2d(L, x, y);
return 1;
}
static int point2d_add(lua_State *L) {
point2d* lhs = luaL_checkudata(L, 1, POINT2D_CLASS);
point2d* rhs = luaL_checkudata(L, 2, POINT2D_CLASS);
create_point2d(L, lhs->x + rhs->x, lhs->y + rhs->y);
return 1;
}
static int point2d_sub(lua_State *L) {
point2d* lhs = luaL_checkudata(L, 1, POINT2D_CLASS);
point2d* rhs = luaL_checkudata(L, 2, POINT2D_CLASS);
create_point2d(L, lhs->x - rhs->x, lhs->y - rhs->y);
return 1;
}
static int point2d_setx(lua_State *L) {
point2d* pnt = luaL_checkudata(L, 1, POINT2D_CLASS);
int x = luaL_checkinteger(L, 2);
pnt->x = x;
return 0;
}
static int point2d_sety(lua_State *L) {
point2d* pnt = luaL_checkudata(L, 1, POINT2D_CLASS);
int y = luaL_checkinteger(L, 2);
pnt->y = y;
return 0;
}
static int point2d_getx(lua_State *L) {
point2d* pnt = luaL_checkudata(L, 1, POINT2D_CLASS);
lua_pushinteger(L, pnt->x);
return 1;
}
static int point2d_gety(lua_State *L) {
point2d* pnt = luaL_checkudata(L, 1, POINT2D_CLASS);
lua_pushinteger(L, pnt->y);
return 1;
}
static int point2d_tostring(lua_State *L) {
point2d* pnt = luaL_checkudata(L, 1, POINT2D_CLASS);
lua_pushfstring(L, "Point2D(%d, %d)", pnt->x, pnt->y);
return 1;
}
static void register_point2d_methods(lua_State *L) {
static const luaL_Reg point2d_methods[] = {
{ "Add", point2d_add },
{ "Sub", point2d_sub },
{ "SetX", point2d_setx },
{ "SetY", point2d_sety },
{ "GetX", point2d_getx },
{ "GetY", point2d_gety },
{ "__add", point2d_add },
{ "__sub", point2d_sub },
{ "__tostring", point2d_tostring },
{ NULL, NULL }
};
luaL_newmetatable(L, POINT2D_CLASS);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, point2d_methods, 0);
lua_pop(L, 1);
}
LUALIB_API int luaopen_geom(lua_State *L) {
static const luaL_Reg geom_lib[] = {
{ "Point2D", point2d_constructor },
{ NULL, NULL }
};
register_point2d_methods(L);
luaL_newlib(L, geom_lib);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment