zoukankan      html  css  js  c++  java
  • Lua 和 C++ 交互

    step1、搭建好vs和lua相交互的环境:

    1.下载一个lua5.3的源码;

    2.有Lua_lib.lib这个文件;

    3.开始配置:

    鼠标放在工程名那:

    右键选属性:

     

    把包含目录点开进行编辑:

     

    地址就选上面有源码的文件路径。

    如上,把引用目录点开进行编辑地址是选lib文件的地址

    如上,把库目录点开进行编辑地址也是lib文件的地址

    step2、给这个工程添加头文件:

    extern "C" {
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
    };

    这样前期准备工作就做好了。

    (一)cpp文件中调用lua文件的函数:

    <.lua文件>

    function Add(a,b)
         return a+b;
    end

    <.cpp文件>

    #include <iostream>
    using namespace std;
    #include"_lua.h"
    static lua_State *L = NULL;
    int ladd(int x, int y) 
    {   
    int sum;   lua_getglobal(L, "Add");   lua_pushinteger(L, x);   lua_pushinteger(L, y);   lua_call(L, 2, 1); //两个参数一个返回值   sum = (int)lua_tointeger(L, -1); //从栈顶取得返回值   lua_pop(L, 1);   return sum; } int main()
    {   L
    = luaL_newstate();   luaL_openlibs(L);   luaL_dofile(L, "D:\Work\Lua\CcallLua\sum.lua");   int sum = ladd(10, 20);   cout << "sum=" << sum << endl;   lua_close(L);   system("pause");   return 0; }

    (二)lua文件中调用cpp文件:

    <.cpp文件>

    //待Lua调用的C注册函数
    
    static int add2(lua_State* L)
    {
      double op1 = luaL_checknumber(L,1);//检查某个参数是否为一个数字
      double op2 = luaL_checknumber(L,2);
      //将函数的结果压入栈中。如果有多个返回值,可以在这里多次压入栈中。
      lua_pushnumber(L,op1 + op2);
      return 1;
    }
    
    
    //待Lua调用的C注册函数。
    static int sub2(lua_State* L)
    {
      double op1 = luaL_checknumber(L,1);
      double op2 = luaL_checknumber(L,2);
      lua_pushnumber(L,op1 - op2);
      return 1;
    }
    
    
    //待Lua调用的C注册函数。
    static int l_sin (lua_State *L) 
    {   
    double d = lua_tonumber(L, 1);   lua_pushnumber(L, sin(d));   return 1; } int main() {   lua_State *L = luaL_newstate();   luaL_openlibs(L);   //将指定的函数注册为Lua的全局函数变量,其中第一个字符串参数为Lua代码   //在调用C函数时使用的全局函数名,第二个参数为实际C函数的指针。   lua_register(L, "add2", add2);   lua_register(L, "sub2", sub2);   lua_register(L, "l_sin", l_sin);   //在注册完所有的C函数之后,即可在Lua的代码块中使用这些已经注册的C函数了。   luaL_dofile(L, "D:\Work\Lua\CcallLua\sum.lua");   lua_close(L);   return 0; }

    <.lua文件>

    function show()
       print("--------------------")
       print(add2(1.0,2.0))
       print(sub2(20.1,19))
       print(l_sin(1))
    end
    
    
    show()
  • 相关阅读:
    UVALive 5966 Blade and Sword -- 搜索(中等题)
    UVA 12380 Glimmr in Distress --DFS
    【转】最长回文子串的O(n)的Manacher算法
    UVA 12382 Grid of Lamps --贪心+优先队列
    UVA 12377 Number Coding --DFS
    高斯消元模板
    图的全局最小割的Stoer-Wagner算法及例题
    逻辑运算符短路特性的应用
    为什么在 Java 中用 (low+high)>>>1 代替 (low+high)/2 或 (low+high)>>1 来计算平均值呢?好在哪里?
    数据库读写分离和数据一致性的冲突
  • 原文地址:https://www.cnblogs.com/cjn123/p/10666144.html
Copyright © 2011-2022 走看看