Thursday, May 03, 2007

為Lua新增函式呼叫

我想說要新增一個Table叫"CSH300CLibrary",那在下有個成員函式(這樣稱呼好像不洽當),叫"MessageBox",那查到有網頁提到如何做:

Lua 語言和C集成調研小結

那也可看官網的資料:

Programming in Lua : Table Manipulation

所以結果會是醬"CSH300CLibrary.MessageBox"去呼叫,希望能今天搞定!!那努力的結果,好像還是不行,只有去看"io.read"是如何做,源碼如下:

LUALIB_API int luaopen_io (lua_State *L) {
    luaL_openlib(L, LUA_OSLIBNAME, syslib, 0);
    createmeta(L);
    lua_pushvalue(L, -1);
    luaL_openlib(L, LUA_IOLIBNAME, iolib, 1);
    /* put predefined file handles into `io' table */
    registerfile(L, stdin, "stdin", IO_INPUT);
    registerfile(L, stdout, "stdout", IO_OUTPUT);
    registerfile(L, stderr, "stderr", NULL);
    return 1;
}
那其中 "iolib" 如下:

static const luaL_reg iolib[] = {
    {"input", io_input},
    {"output", io_output},
    {"lines", io_lines},
    {"close", io_close},
    {"flush", io_flush},
    {"open", io_open},
    {"popen", io_popen},
    {"read", io_read},
    {"tmpfile", io_tmpfile},
    {"type", io_type},
    {"write", io_write},
    {NULL, NULL}
};
仿造上面的寫法就可以搞定,另外為了能跟隨lua的習慣,原本"CSH300CLibrary.MessageBox"改成"sh300.msgbox"。

No comments: