hello lua

http://manual.luaer.cn/

http://www.lua.org/pil/contents.html

 1 #include <cstdio>
 2 #include <string>
 3 extern "C"{
 4 #include "lua.h"
 5 #include "lauxlib.h"
 6 #include "lualib.h"
 7 };
 8 
 9 
10 static int foo(lua_State* L)
11 {
12     int n = lua_gettop(L);
13     lua_Number sum = 0;
14     int i = 0;
15     for (i=1; i <= n; ++i)
16     {
17         if (!lua_isnumber(L, i))
18         {
19             lua_pushstring(L, "incorrect argument");
20             lua_error(L);
21         }
22         sum += lua_tonumber(L, i);
23     }
24     lua_pushnumber(L, sum/n);
25     lua_pushnumber(L, sum);
26     return 2;
27 }
28 
29 int main(void)
30 {
31     char buff[256] = {0};
32     int error = 0;
33 
34     lua_State *L = luaL_newstate();
35     luaL_openlibs(L);
36 
37     lua_createtable(L, 0, 0);
38     lua_setfield(L, LUA_GLOBALSINDEX, "t_test");
39     lua_getfield(L, LUA_GLOBALSINDEX, "t_test");
40     lua_pushstring(L, "test");
41     lua_setfield(L, -2, "test");
42 
43     lua_pushcfunction(L, foo);
44     lua_setfield(L, -2, "foo");
45     
46     lua_settop(L, 0);
47 
48     while (fgets(buff, sizeof(buff), stdin) != NULL)
49     {
50         size_t sz = strlen(buff);
51         error = luaL_loadbuffer(L, buff, sz, "line")
52                 || lua_pcall(L, 0, 0, 0);
53         if (error)
54         {
55             fprintf(stderr, "%s", lua_tostring(L, -1));
56             lua_pop(L, 1);
57         }
58     }
59 
60     /*int err = luaL_loadfile(L, "hangj.lua") || lua_pcall(L, 0, LUA_MULTRET, 0);
61     if (err)
62     {
63         fprintf(stderr, "%s", lua_tostring(L, -1));
64         lua_pop(L, 1);
65     }*/
66 
67     lua_getfield(L, LUA_GLOBALSINDEX, "hangj");
68     const char* str = lua_tostring(L, -1);
69     if (str)
70         printf("hangj: %s\n", str);
71     lua_remove(L, -1);
72 
73     lua_close(L);
74     getchar();
75     return 0;
76 }
int lua_gettop (lua_State *L);

返回栈顶元素的 index,因为 index 是从 1 开始的,所以返回值等于栈中元素的个数。0 表示空栈。