C/C++教程

lua结合c/c++示例

本文主要是介绍lua结合c/c++示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

lua部分

#!/bin/lua
mystr="I'm lua"
myTable={name="xiaoming",id=12345}
function print_hello()
    print("hello world")                                                                                                                                    
end

function _add(a,b)
    return a+b 
end

C/C++

  • 方式一引入包含lua头文件的.h文件
#ifndef MLUA_H_
#define MYLUA_H_
extern "C"
{
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lauxlib.h>
#include <luajit-2.0/lualib.h>
}
#endif
#include <iostream>
#include <string>
//方式二 #include <luajit-2.0/lua.hpp>
#include "mylua.h"
using namespace std;


int main()
{
    lua_State *L = luaL_newstate();
    if(NULL == L)
    {
        cout<<"Lua 初始化失败"<<endl;
        return -1;
    }
    // 加载相关库文件
    luaL_openlibs(L);

    // 加载lua文件
    if(luaL_loadfile(L,"./data1.lua"))
    {
        cout<<"Lua 文件加载失败"<<endl;
    }else{
        // 执行lua文件
        if(lua_pcall(L,0,0,0))
        {
            cerr<<lua_tostring(L,-1)<<endl;
        }else{
            // 获取值
            lua_getglobal(L,"mystr");

            string str = lua_tostring(L,-1);
            cout<<str<<endl;

            // 获取表中的数据
            lua_getglobal(L,"myTable");
            lua_getfield(L,-1,"name");
            cout<<lua_tostring(L,-1)<<endl;

            lua_getglobal(L,"myTable");
            lua_getfield(L,-1,"id");
            cout<<lua_tonumber(L,-1)<<endl;

            // 调用函数
            lua_getglobal(L,"print_hello");
            lua_pcall(L,0,0,0);

            // 调用计算函数
            lua_getglobal(L,"_add");
            lua_pushnumber(L,10);
            lua_pushnumber(L,29);

            if(lua_pcall(L,2,1,0))
            {
                cout<<lua_tostring(L,-1)<<endl;
                lua_close(L);
            }else{
                if(lua_isnumber(L,-1))
                {
                    cout<<lua_tonumber(L,-1)<<endl;
                }
            }
        }
    }
    lua_close(L);
    return 0;
}
这篇关于lua结合c/c++示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!