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

  • 相关阅读:
    luogu1196 银河英雄传说 (并查集)
    [BZOJ2243][SDOI2011]染色
    [BZOJ1879] [Sdoi2009]Bill的挑战
    [Noip2003] 侦探推理
    [Noip2005] 篝火晚会
    [JZOJ100047] 【NOIP2017提高A组模拟7.14】基因变异
    [九省联考2018]一双木棋chess
    [Noip2009] 靶形数独
    [Luogu2737] [USACO4.1]麦香牛块Beef McNuggets
    [BZOJ3109] [cqoi2013]新数独
  • 原文地址:https://www.cnblogs.com/elitiwin/p/3957860.html
Copyright © 2011-2022 走看看