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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h>
#include "lua.h" #include "lauxlib.h" #include "lualib.h"
typedef struct function_buf_s { char *name; int nargs; int nret; char *chunk; } function_buf;
static function_buf lua_function[] = { {"sayhi", 1, 1, "local name = ...\n" "return string.format('hi %s!', name)\n" }, {"echo", 1, 1, "function echo(msg)\n" " return msg\n" "end\n" "local msg = ...\n" "return echo(msg)\n" }, {NULL, 0, 0,NULL} };
static int sayHi(lua_State *L) {
function_buf *function = &lua_function[0]; int ret = luaL_loadbuffer(L, function->chunk, strlen(function->chunk), function->name); if (ret) { return luaL_error(L, "call loadbuffer fail ret:%d, code:%s", ret, function->chunk); } lua_pushstring(L, "lua"); ret = lua_pcall(L, 1, 1, 0); if (ret != 0) { return luaL_error(L, "lua_pcall fail ret:%d %s", ret, lua_tostring(L, -1)); }
printf("typename %s\n", luaL_typename(L, -1));
if (!lua_isstring(L, -1)) { return luaL_error(L, "lua_pcall ret not string"); } const char *msg = lua_tostring(L, -1); lua_pop(L, -1); lua_pushfstring(L, "sayhi say:%s", msg); return 1; }
static int common_entry(lua_State *L) { if (!lua_isstring(L, 1)) { return luaL_error(L, "first arg should be function name, string type"); } const char * function_name = lua_tostring(L, 1); function_buf *function = lua_function; for (;function->name; function++) { if (!strcmp(function->name, function_name)) break; } if (!function->name) { return luaL_error(L, "not found:%s function in array", function_name); }
int ret = luaL_loadbuffer(L, function->chunk, strlen(function->chunk), function->name); if (ret) { return luaL_error(L, "call loadbuffer fail ret:%d, code:%s", ret, function->chunk); } int i; for(i=2; i <= function->nargs+1; i++) { lua_pushstring(L, lua_tostring(L, i)); }
ret = lua_pcall(L, function->nargs, function->nret, 0); if (ret != 0) { return luaL_error(L, "lua_pcall fail ret:%d %s", ret, lua_tostring(L, -1)); } int nret = function->nret; for (i=-1; i >= -nret; i--){ printf("ret:%d is:%s\n", -i, lua_tostring(L, i)); } return nret; }
static const struct luaL_reg call_function_lib[] = { {"sayHi", sayHi}, {"common_entry", common_entry}, {NULL, NULL} };
int luaopen_call_function(lua_State *l) { luaL_openlib(l, "call_function", call_function_lib, 0); return 1; }
|