C/C++调用lua的table,table包含函数,table和变量

来源:互联网 发布:ios11.2 软件打不开 编辑:程序博客网 时间:2024/05/21 11:01

//环境:乌班图4.04

//安装软件:sudo apt-get install lua5.1和sudo apt-get install liblua5.1-dev

//源文件分别为c.c和peizhi.lua

//编译:g++ c.c -llua5.1     

//-llua5.1:链接lua5.1的库

/*

下面是c.c的代码

*/


#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>
#include <stdlib.h>
//#include "peizhi.h"
#include <iostream>
using namespace std;

int main()
{
    const char *peizhi = "peizhi.lua";
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    //加载lua文件并执行lua文件
    if (luaL_loadfile(L, peizhi) || lua_pcall(L, 0, 0, 0))
    {
        printf("error..........\n");
        exit(0);
    }

    //将protocol这个变量放在栈顶,对应lua文件中的protocol这个table
    lua_getglobal(L, "protocol");
    //如果protocol不是一个table,返回错误
    if (!lua_istable(L, -1))
    {
        printf("protocol is not table\n");
        exit(0);
    }

    //往栈中压入temp,现在temp字段在栈顶
    lua_pushstring(L, "temp");
    //把protocol这张表中temp对应的值(TEMP = 345)放在栈顶,弹出压入的temp变量
    lua_gettable(L, -2);
    if (!lua_isnumber(L, -1))
    {
        printf("invalid componet in protocol.....\n");
        exit(0);
    }
    
    //获取栈顶的值
    printf("temp = %d\n", (int)lua_tonumber(L, -1));
    //从栈顶把temp的值弹出,现在protocl又在栈顶了
    lua_pop(L, 1);

    //往栈中压入func,现在func字段在栈顶
    lua_pushstring(L, "func");
    //把protocol这张表中func对应于的值(f,这是个函数)放在栈顶,弹出func字段
    lua_gettable(L, -2);
    assert(lua_isfunction(L, -1));
    //压入f函数的2个行参,
    lua_pushstring(L, "12");
    lua_pushstring(L, "24");
    //lua_pcall(L, 2, 1, 0)中的2代表2个形参,1代表1个返回值,如果函数执行正确返回值为0,并且f和形参从栈顶弹出,返回值放在栈顶
    if (lua_pcall(L, 2, 1, 0) != 0)
    {
        printf("error running function func:%s\n", lua_tostring(L, -1));
    }

    //判断栈顶值是否是number类型
    if (!lua_isnumber(L, -1))
    {
        printf("function func must return a number\n");
        exit(0);
    }

    printf("result = %d\n", (int)lua_tonumber(L, -1));
    //将栈顶的值弹出,现在protocol又在栈顶了
    lua_pop(L, 1);

    //压入BLUE字段在栈顶
    lua_pushstring(L, "BLUE");
    //把protocol这张表中BLUE对应的值blue这张表放在栈顶
    lua_gettable(L, -2);
    //把字符串“r”压入栈顶
    lua_pushstring(L, "r");
    //把BLUE中r对应的值放在栈顶,相当于blue[r]
    lua_gettable(L, -2);
    printf("result = %d\n", (int)lua_tonumber(L, -1));

    //从栈顶把r字段对应的值弹出,现在blue这张table在栈顶
    lua_pop(L, 1);
    //从栈顶把blue这张table弹出,现在protocl又在栈顶
    lua_pop(L, 1);

    lua_pushstring(L, "a");
    lua_gettable(L, -2);
    printf("temp = %d\n", (int)lua_tonumber(L, -1));
    lua_pop(L, 1);

    return 0;
}



-------------------------------------------------------

peizhi.lua



blue = {r = 3, g = 1, b = 8}

function f(x, y)
    return x + y
end


local TEMP = 345

protocol =
{
    temp = TEMP,
    BLUE = blue,
    func = f,
    a = 32
}







原创粉丝点击