好记性不如铅笔头

C && C++, Lua, 编程

Lua快速学习笔记:在Lua脚本中调用C/C++函数的API

CONTENTS

备注:

1 本笔记只记录了LUA的一小部分内容,对于LUA的描述并不全面,以后随用随增加吧。
2 本笔记参考《Lua程序设计 第二版》,截图和代码属于原作者所有。
3 作者初学LUA,经验和能力有限,笔记可能有错误,还请各位路过的大牛们给予指点。
4 API参考网址:参考网址: http://www.codingnow.com/2000/download/lua_manual.html

函数格式:

lua_CFunction:
typedef int (*lua_CFunction) (lua_State *L);
为了正确的和 Lua 通讯,C 函数必须使用下列 定义了参数以及返回值传递方法的协议: C 函数通过 Lua 中的堆栈来接受参数,参数以正序入栈(第一个参数首先入栈)。 因此,当函数开始的时候, lua_gettop(L) 可以返回函数收到的参数个数。 第一个参数(如果有的话)在索引 1 的地方,而最后一个参数在索引 lua_gettop(L) 处。 当需要向 Lua 返回值的时候,C 函数只需要把它们以正序压到堆栈上(第一个返回值最先压入), 然后返回这些返回值的个数。 在这些返回值之下的,堆栈上的东西都会被 Lua 丢掉。 和 Lua 函数一样,从 Lua 中调用 C 函数也可以有很多返回值。
下面这个例子中的函数将接收若干数字参数,并返回它们的平均数与和:

     static int foo (lua_State *L) {
       int n = lua_gettop(L);    /* 参数的个数 */
       lua_Number sum = 0;
       int i;
       for (i = 1; i <= n; i++) {
         if (!lua_isnumber(L, i)) {
           lua_pushstring(L, "incorrect argument");
           lua_error(L);
         }
         sum += lua_tonumber(L, i);
       }
       lua_pushnumber(L, sum/n);   /* 第一个返回值 */
       lua_pushnumber(L, sum);     /* 第二个返回值 */
       return 2;                   /* 返回值的个数 */
     }

lua_pushcfunction:

void lua_pushcfunction (lua_State *L, lua_CFunction f);
将一个 C 函数压入堆栈。 这个函数接收一个 C 函数指针,并将一个类型为 function 的 Lua 值 压入堆栈。当这个栈顶的值被调用时,将触发对应的 C 函数。
注册到 Lua 中的任何函数都必须遵循正确的协议来接收参数和返回值 (参见 lua_CFunction)。
lua_pushcfunction 是作为一个宏定义出现的:

     #define lua_pushcfunction(L,f)  lua_pushcclosure(L,f,0)

lua_register:

void lua_register (lua_State *L, const char *name, lua_CFunction f);
把 C 函数 f 设到全局变量 name 中。 它通过一个宏定义:
     #define lua_register(L,n,f) \
            (lua_pushcfunction(L, f), lua_setglobal(L, n))

luaL_Reg:

typedef struct luaL_Reg {
  const char *name;
  lua_CFunction func;
} luaL_Reg;
Type for arrays of functions to be registered by luaL_register. name is the function name and func is a pointer to the function. Any array of luaL_Reg must end with an sentinel entry in which both name and func are NULL.

luaL_register:

void luaL_register (lua_State *L,
                    const char *libname,
                    const luaL_Reg *l);
Opens a library.
When called with libname equal to NULL, it simply registers all functions in the list l (see luaL_Reg) into the table on the top of the stack.
When called with a non-null libname, luaL_register creates a new table t, sets it as the value of the global variable libname, sets it as the value of package.loaded[libname], and registers on it all functions in the list l. If there is a table in package.loaded[libname] or in variable libname, reuses this table instead of creating a new one.
In any case the function leaves the table on the top of the stack.

发表评论

3 × 4 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据