tolua++初探(二)

來源:互聯網
上載者:User
    tolua++的源碼包中有很多測試例子。這裡我用更最簡單的例子來學習。
    第一個例子是數組。僅僅是把C++中的一個數組匯出到Lua中,可以在指令碼中訪問並修改。
    tarray.pkg檔案:
   

$#include "tarray.h"
extern int g_Arr[10]@Arr;

     很簡單,$#include "tarray.h",包含實際的C標頭檔,這個語句會去掉$符號,直接插入到tolua++.exe產生的C檔案中。文檔中說$lfile,$cfile,$ifile會特別處理,我實驗了下,不像說的那個樣子。
    extern int g_Arr[10]@Arr,tolua++會分析這一句,將g_Arr[10]映射到lua中的Arr上。其中@後面是你想在lua中看到的變數名。
    tarray.h檔案也只有一句:

#ifndef _TESTARRAY_H
#define _TESTARRAY_H
extern int g_Arr[10];
#endif

    g_Arr的執行個體在一個cpp檔案中。

    用tolua++.exe產生用於匯出c++對象到lua指令碼中的CPP檔案:

tolua++.exe -n tarray -o tarray.cpp tarray.pkg

    -n tarray選項指定包的名字為tarray。如果不用-n顯式指定,tolua++.exe會產生一個和pkg檔案名稱一樣的包名,同時產生tolua_**_open(lua_State*)入口函數。
   
    將此CPP檔案加入工程。
    在工程中加入lua5.1.lib,tolua++.lib,包含lua.hpp,tolua++.h,然後寫點測試代碼,就可以編譯了。程式主檔案array.cpp:

#include "stdafx.h"
#include "lua.hpp"
int tolua_tarray_open (lua_State* tolua_S);
#include "tarray.h"
int g_Arr[10]=...{0};
int _tmain(int argc, _TCHAR* argv[])
...{
    lua_State * L = lua_open();
    int i=0;
    for(i=0; i<10; i++) g_Arr[i] = i;
    luaopen_base(L);
    tolua_tarray_open(L);
    luaL_dofile(L, "../scripts/array.lua");
    printf("now in c++, re-show Arr: ");
    for(i=0; i<10; i++)
        printf("%d ", g_Arr[i]);
    printf(" ");
        
    lua_close(L);
    return 0;
}

    luaopen_tarray_open是必須要調用的,tolua++.exe根據你命令列中指定的名字產生tolua_**_open函數。該函數用來匯出c++對象到lua指令碼中,所以必須在你執行lua指令碼之前調用。函數的原型在由tolua++.exe產生的cpp檔案中。

    指令檔array.lua內容如下:

print("now in lua script!   try to print 'Arr' by name:")
print(Arr)
--print contents of Arr
print("now print 'Arr':")
for i=0,9 do print(Arr[i]) end
--change contents of Arr
print("now change the Arr.")
for i=0,9 do Arr[i] = i*2 end

    第一個例子到此為止。編譯後可以進行測試了。
    我針對DEBUG和release版本產生了不同的DLL和LIB檔案,好用於測試。總結一下步驟:
    1.編寫C標頭檔,定義想匯出的對象
    2.編寫pkg檔案,包含之前的C標頭檔,用tolua++可識別的規則定義你要匯出的對象
    3.用tolua++.exe產生CPP檔案
    4.將3產生的檔案,1中的標頭檔,tolua++的標頭檔,lua的標頭檔及相關的庫加入工程。
    5.編寫lua指令檔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.