Created
June 16, 2013 04:35
-
-
Save zhzhxtrrk/5790782 to your computer and use it in GitHub Desktop.
简单的嵌入lua,留作模板吧……
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <lua.h> | |
#include <lauxlib.h> | |
#include <lualib.h> | |
#include <math.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define TOY_MODULE_NAME "toy" | |
static int l_toy_new(lua_State *L) { | |
double value; | |
double *toy_obj; | |
value = luaL_checknumber(L, 1); | |
toy_obj = lua_newuserdata(L, sizeof(double)); | |
*toy_obj = value; | |
luaL_getmetatable(L, TOY_MODULE_NAME); | |
lua_setmetatable(L, -2); | |
printf("Hello, %f\n", value); | |
return 1; | |
} | |
static int l_toy_gc(lua_State *L) { | |
double *user_data = luaL_checkudata(L, 1, TOY_MODULE_NAME); | |
printf("goodbye, %f\n", *user_data); | |
return 0; | |
} | |
static int l_toy_sin(lua_State *L) { | |
double *arg = luaL_checkudata(L, -1, TOY_MODULE_NAME); | |
lua_pushnumber(L, sin(*arg)); | |
return 1; | |
} | |
static luaL_Reg l_toy_meta_functions[] = { | |
{ "sin", l_toy_sin }, | |
{ "__gc", l_toy_gc }, | |
{ NULL, NULL } | |
}; | |
static luaL_Reg l_toy_module_functions[] = { | |
{ "new", l_toy_new }, | |
{ NULL, NULL } | |
}; | |
static int l_toy_module(lua_State *L) { | |
lua_newtable(L); | |
luaL_setfuncs(L, l_toy_module_functions, 0); | |
return 1; | |
} | |
static void l_register_toy(lua_State *L) { | |
luaL_newmetatable(L, TOY_MODULE_NAME); | |
{ | |
lua_pushstring(L, "__index"); | |
lua_pushvalue(L, -2); | |
lua_settable(L, -3); | |
luaL_setfuncs(L, l_toy_meta_functions, 0); | |
} | |
lua_pop(L, 1); | |
luaL_requiref(L, "toy", l_toy_module, 0); | |
lua_pop(L, 1); | |
} | |
int main(int argc, char** argv) { | |
lua_State *L = luaL_newstate(); | |
luaL_openlibs(L); | |
l_register_toy(L); | |
printf("%d\n", lua_gettop(L)); | |
if (luaL_dofile(L, "test.lua")) { | |
printf("%s\n", luaL_checkstring(L, -1)); | |
} | |
printf("%d\n", lua_gettop(L)); | |
lua_close(L); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment