C/C++ 调用 Lua 函数(非全局函数)

来源:互联网 发布:临淄广电网络客服电话 编辑:程序博客网 时间:2024/04/28 11:40

C/C++ 调用 Lua 函数有两种:

1, Lua 脚本里,没有local 修饰的函数,即为全局函数

2, Lua 脚本里,有local 修饰的函数,即为局部函数

其实调用函数和取Lua里的变量是一样的,网上讲得最多的是调用全局函数,这里主要讲调用非全局函数(或是变量)。

如有脚本: test.lua

--定义了一个全局表
COM = {}

--定义了一个局部函数
local function add(a, b)
    print("a = "..a);
    print("b = "..b);
    return a + b;
end

COM = 
{
    width = 2550,
    myAdd = add,
}


有c文件: main.c

#include <stdio.h>
#include <stdlib.h>

#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"


int main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    if(luaL_loadfile(L, "test.lua"))
    {
        printf("load file: hello.lua faild...\n");
        lua_close(L);
        return 1;
    }
    lua_pcall(L, 0, 0, 0); /* 前面这几步都基本固定 */
    
    lua_getglobal(L, "COM");         /* 先找到表 */
    if(lua_type(L, -1) != LUA_TTABLE)    
    {
        printf("can not find table: COM \n");
        lua_close(L);
        return 1;
    }

    lua_pushstring(L, "myAdd");    /* 要找的函数名入栈 */
    lua_gettable(L, -2);
    if(lua_type(L, -1) != LUA_TFUNCTION)    /* 找到的是否是函数 */
    {
        printf("find myAdd is not a function.\n");
        lua_close(L);
        return 1;
    }

    lua_pushnumber(L, 111);
    lua_pushnumber(L, 222);
    lua_pcall(L, 2, 1, 0);    /* 传参, 执行 */
    printf("call lua function add() and result: %d\n", (int)lua_tonumber(L, -1));

    lua_close(L);
    return 0;
}


执行结果

[root@localhost lua_call_c]# ./a.out 
a = 111
b = 222
call lua function add() and result: 333


系统:CentOS 6.5

内核: Linux  2.6.32-431.el6.i686

gcc : gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)