1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include <lualib.h> #include <lauxlib.h>
#include <stdio.h> #include <sys/time.h>
static int (lua_State * L) { double a = luaL_checknumber(L, 1); printf("第一个参数:%fn", a);
double b = luaL_checknumber(L, 2); printf("第二个参数:%fn", b);
lua_pushnumber(L, a + b);
return 1; }
static int i_swap(lua_State * L) { int i = lua_tointeger(L, 1); int j = lua_tointeger(L, 2); printf("%d 和 %d 交换位置n", i, j);
lua_pushinteger(L, j); lua_pushinteger(L, i);
return 2; }
static int i_fib(lua_State * L) { lua_Integer sum = 0; lua_Integer a = 0; lua_Integer b = 0;
int n = lua_tointeger(L, 1); int i = 0; while (i <= n) { i++; if (i == 1) { a = 0; b = 1; } sum = a + b; a = b; b = sum; }
lua_pushinteger(L, sum); return 1; }
static int i_time(lua_State * L) { struct timeval tv; gettimeofday( &tv, NULL ); double t = tv.tv_sec + (double)((int)(tv.tv_usec*0.001) * 0.001);
lua_pushinteger(L, (lua_Integer)(t * 1000)); return 1; }
int luaopen_mylib(lua_State * L) { lua_register(L, "add", i_add); lua_register(L, "swap", i_swap); lua_register(L, "fib_c", i_fib); lua_register(L, "current_time", i_time); return 0; }
|