zoukankan      html  css  js  c++  java
  • 用VC加载Lua.lib,C++调用lua脚本函数

    1、先去lua.org官方网站上去下载一个win32的vc10库(vs2010),如果你是其他版本请按照实际需求下载。

    2、创建一个新的 空控制台应用程序

    3、复制lualib下的include所有.h文件到项目中,并且全部加入到header files和source files中。

    4、新建一个main.cpp文件到source files中:加入C++代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    extern "C" {
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
    }
    #pragma comment (lib,"lua52.lib")
    
    void MaxMin(lua_State* L, int x, int y)
    {
        lua_getglobal(L, "MaxMin");
        //参数1
        lua_pushnumber(L, x);
        //参数2
        lua_pushnumber(L, y);
    
        //2个参数,3个返回值
        lua_pcall(L, 2, 3, 0);
        const char* c = lua_tostring(L, -3);
        lua_Number n1 = lua_tonumber(L, -2);
        lua_Number n2 = lua_tonumber(L, -1);
    
        //cout<<c<<"  "<<"Max = "<<n1<<", Min = "<<n2<<endl;
        printf("%s Max = %f Min = %f\n", c, n1, n2);  
        //元素出栈
        lua_pop(L, 3);
    }
    
    void printHello(lua_State* L)
    {
        lua_getglobal(L, "printHello");
    
        lua_pcall(L, 0, 1, 0);
        const char* c = lua_tostring(L, -1);
    
        printf("%s",c);  
        //元素出栈
        lua_pop(L, 1);
    }
    
    int main()
    {
        lua_State* L = luaL_newstate();
        if(!luaL_loadfile(L, "C:\\vsproject\\lua\\test\\testlua.lua"))
        {
            if(!lua_pcall(L, 0, 0, 0))
            {
                MaxMin(L, 1, 2);
                MaxMin(L, 3, 3);
                MaxMin(L, 9, 8);
                printHello(L);
            }
        }
        lua_close(L);
        system("pause");
        return 0;
    }

    5、然后再C:\\vsproject\\lua\\test\\ 目录下新建一个文件testlua.lua(也可以放在你想要放的地方),加入lua代码:

    function MaxMin(x, y)
        if x > y then
            return "x > y", x, y
        elseif x == y then
            return "x = y", x, y
        else
            return "y > x", y, x
        end
    end
    function printHello()
        return "Hello, world!"
    end

    然后运行结果:

  • 相关阅读:
    JS学习笔记ZT
    一条经典的汇总的sql
    sql 日期的转换
    微软.net安装失败时出现的问题
    sql 换行
    js 代码
    学习笔记
    decimal 的使用
    功能最完善,代码最简洁的选项卡代码(div+css)
    sql字母排序
  • 原文地址:https://www.cnblogs.com/hyb1/p/3081615.html
Copyright © 2011-2022 走看看