zoukankan      html  css  js  c++  java
  • 在CC++中调用Lua

    1.CC++程序中调用Lua函数

    方法一:

    #include "stdafx.h"

    #include <stdio.h>

    #include <string.h>

    #include <stdlib.h>

    #include "lua.hpp"

    const char* lua_function_code = "function dealStr(str)  

                            return string.gsub(str,"World","lua")       

                      end";  

    void call_function(lua_State* L)

    {    

         if (luaL_dostring(L,lua_function_code))

        {  

            printf("Failed to run lua code. ");  

            return;  

        }

       char str[512] = "Hello World!";  

       lua_getglobal(L,"dealStr");  

       lua_pushlstring(L,str,512);  

       if(lua_pcall(L,1,1,0))  

      {   

          printf("error is %s. ",lua_tostring(L,-1));   

          return;  

      }  

      if(!lua_isstring(L,-1))  

      {   

          printf("function 'add' must return a string. ");   

          return;  

      }  

      size_t len;  

      const char* ret = lua_tolstring(L,-1,&len);  

      lua_pop(L,-1); //弹出返回值。

      printf("The result of call function is %s. ",ret);

    }    

    int main()

    {    

        lua_State* L = luaL_newstate();  

        luaL_openlibs(L);  

        call_function(L);  

        lua_close(L);  

        system("pause");    

        return 0;

    }

    方法二:

    #include "stdafx.h"

    #include <stdio.h>

    #include <string.h>

    #include <stdlib.h>

    #include "lua.hpp"

    void call_function(lua_State* L)

    {    

      luaL_dofile(L, "test.lua");

      char str[512] = "Hello World!"; 

       lua_getglobal(L,"dealStr"); 

       lua_pushlstring(L,str,512); 

       if(lua_pcall(L,1,1,0)) 

      {  

          printf("error is %s. ",lua_tostring(L,-1));  

          return; 

      } 

      if(!lua_isstring(L,-1)) 

      {  

          printf("function 'add' must return a string. ");  

          return; 

      } 

      size_t len; 

      const char* ret = lua_tolstring(L,-1,&len); 

      lua_pop(L,-1); //弹出返回值。

      printf("The result of call function is %s. ",ret);

    }    

    int main()

    {    

        lua_State* L = luaL_newstate(); 

        luaL_openlibs(L); 

        call_function(L); 

        lua_close(L); 

        system("pause");    

        return 0;

    }

    test.lua

    function dealStr(str)
       return string.gsub(str,"World","lua")
    end

  • 相关阅读:
    第三篇 从EXCEL电子表格到数据库
    第二篇 顾问实施ERP与医生看病过程类比
    第一篇 ERP是什么?-从道的层面浅谈我的理解
    Order to Cash Process
    Back to Back Order Process
    OracleApps 什么是Back to Back Order?
    三方贸易-drop ship
    Oracle Order Management DropShip Flow for R12
    OracleApps Dropship 流程
    geetoo编译安装
  • 原文地址:https://www.cnblogs.com/elitiwin/p/3957860.html
Copyright © 2011-2022 走看看