AKever

导航

使用 tolua++ 将C++对象暴露给lua

使用 tolua++ 将C++对象暴露给lua

vs2012 + lua5.1.4 + tolua++

----------------------------------------------------------------------------------------------

1. 收集资料:

lua 5.1.4(cocos2dx 3.6), tolua++源码(CSDN下载-源码+lib+exe)

2. 将lua5.1.4编译成lib库 

3. 编写类文件 "UsingIt.h"

#ifndef __MY_CLASS_H__
#define __MY_CLASS_H__
// file: UsingIt.h
#include <iostream>
class my_class
{
public:
    void greet()
    {
        std::cout << "Hello World!" << std::endl;
    }
};
#endif //__MY_CLASS_H__

4.编写 "mylib.pkg"

// file: mylib.pkg
$pfile "UsingIt.h"

class my_class
{
    my_class();
    ~my_class();

    void greet();
};

5.新建项目工程(Empty-Project) 新建一下文件夹,并加入 Additional Include Directory(C\C++ -> General)

lua tolua test (lib)

6.添加文件

将lua的头文件(.h)加入lua, tolua文件加入tolua(去除tolua.c), 将UgingIt.h, mylib.pkg, tolua++.exe加入test

a> 将lua.lib, tolua++.lib, tolua++D.lib加入lib文件
b> lib文件夹路径添加到 Additional Libraies Directories(Linker->General) 
c> 3个lib文件名添加到 Additional Dependencies(Linker Input)

7.使用tulua++.exe生成mylib.h文件(生成mylib.cpp文件出现error)

tolua++ -n mylib -o mylib.h mylib.pkg
生成的mylib.h文件 添加:
#include "UsingIt.h" (奇怪: 有类的使用,没include)

8.在项目目录下新建mytest.lua文件

local my = my_class()
my:greet()

9.编写main.cpp文件,  运行

#include "main.h"

#include <iostream>
#include <tolua++.h>
extern "C" {
#include <lua.h>
#include <lauxlib.h>
}
//#include "test/UsingIt.h"
#include "test/mylib.h"

int main(int arg, int args[])
{
    lua_State* L = lua_open();
    luaL_newstate();

    tolua_mylib_open(L); // 打开mylib
    luaL_dofile(L, "mytest.lua"); // 执行脚本文件

    lua_close(L);

    system("pause");
    return 0;
}

项目工程截图

 

-- THE END !!

 

posted on 2015-06-24 14:56  AKever  阅读(567)  评论(0)    收藏  举报