2010-04-25 71 views

回答

5
void register_c_function(char const * const tableName, char const * const funcName, CFunctionSignature funcPointer) 
{ 
    lua_getfield(lstate, LUA_GLOBALSINDEX, tableName); // push table onto stack 
    if (!lua_istable(lstate, -1))      // not a table, create it 
    { 
     lua_createtable(lstate, 0, 1);  // create new table 
     lua_setfield(lstate, LUA_GLOBALSINDEX, tableName); // add it to global context 

     // reset table on stack 
     lua_pop(lstate, 1);     // pop table (nil value) from stack 
     lua_getfield(lstate, LUA_GLOBALSINDEX, tableName); // push table onto stack 
    } 

    lua_pushstring(lstate, funcName);  // push key onto stack 
    lua_pushcfunction(lstate, funcPointer); // push value onto stack 
    lua_settable(lstate, -3);    // add key-value pair to table 

    lua_pop(lstate, 1);      // pop table from stack 
} 
+4

爲什麼不使用luaL_register? – uroc 2010-04-26 13:31:07

20

這是luaL_register()打算做的,用於一個或多個功能。該規範的用法是作爲設置爲C語言編寫的一個模塊的一部分:

/* actual definitions of modA() and modB() are left as an exercise. */ 

/* list of functions in the module */ 
static const luaL_reg modfuncs[] = 
{ 
    { "a", modA}, 
    { "b", modB}, 
    { NULL, NULL } 
}; 

/* module loader function called eventually by require"mod" */ 
int luaopen_mod(lua_State *L) { 
    luaL_register(L, "mod", modfuncs); 
    return 1; 
} 

,其中這將創建一個名爲「國防部」模塊,該模塊有一個名爲mod.amod.b兩種功能。

引述手冊luaL_register(L,libname,l)

當與libname等於叫 NULL,它簡單地登記在列表中的所有 功能l(見luaL_Reg) 到表上 堆棧的頂部。它的所有功能

當與非空libname叫, luaL_register創建新表t, 將其設置全局 變量libname的值,將其設置爲值package.loaded[libname] 和 寄存器在 列表l。如果在 package.loaded[libname]或變量 libname中有表格,則重新使用此表格而不是 創建一個新表格。

在任何情況下,函數都會將表放在堆棧頂部。

luaL_register()可以通過傳遞NULL其第二參數,只要該表是在堆疊的頂部用來放C函數中的任何表。

+0

如果已經有其他字段的mod table,它會在luaL_register()調用之後被擴展或替換爲新的嗎? – 2010-04-26 23:07:38

+0

根據5.1手冊,它將重新使用和更新以前的表格。 – u0b34a0f6ae 2010-04-27 10:21:54

+0

無論是應用於指定的全局表還是應用於堆棧頂部的表,它只會設置函數列表中指定的那些字段進行註冊,並保留其他任何字段不變。區別在於給定全局名稱,如果需要,還會創建表並添加對'package.loaded'的引用。 – RBerteig 2010-04-28 02:03:15