簡體   English   中英

創建后的 Lua c API 更改庫

[英]Lua c API change library after creation

我正在嘗試使用 C API 在 Lua 中包裝 ncurses。 我與工作stdscr指針:這是NULL之前initscr被調用, initscr是從Lua通過我的綁定的設計要求。 所以在驅動程序功能中我這樣做:

// Driver function
LUALIB_API int luaopen_liblncurses(lua_State* L){
    luaL_newlib(L, lncurseslib);

    // This will start off as NULL
    lua_pushlightuserdata(L, stdscr);
    lua_setfield(L, -2, "stdscr");

    lua_pushstring(L, VERSION);
    lua_setglobal(L, "_LNCURSES_VERSION");
    return 1;
}

這按預期工作。 當我需要修改stdscr時,麻煩就來了。 initscr是這樣綁定的:

/*
** Put the terminal in curses mode
*/
static int lncurses_initscr(lua_State* L){
    initscr();
    return 0;
}

我需要修改庫中的stdscr使其不再為空。 Lua端的示例代碼:

lncurses = require("liblncurses");
lncurses.initscr();
lncurses.keypad(lncurses.stdscr, true);
lncurses.getch();
lncurses.endwin();

但是, lncurses.stdscr是 NULL,所以它本質上是在運行keypad(NULL, true);

我的問題是,在創建庫后如何在 Lua 中修改庫值?

您可以使用注冊表

Lua 提供了一個注冊表,這是一個預定義的表,任何 C 代碼都可以使用它來存儲它需要存儲的任何 Lua 值。 注冊表總是位於偽索引LUA_REGISTRYINDEX 任何 C 庫都可以將數據存儲到此表中,但必須注意選擇與其他庫使用的鍵不同的鍵,以避免沖突。 通常,您應該使用包含庫名稱的字符串作為鍵,或者使用包含代碼中 C 對象地址的輕量用戶數據,或者由代碼創建的任何 Lua 對象。 與變量名一樣,以下划線開頭的字符串鍵后跟大寫字母是為 Lua 保留的。

創建時在注冊表中存儲對模塊表的引用。

LUALIB_API int luaopen_liblncurses(lua_State* L) {
    luaL_newlib(L, lncurseslib);

    // This will start off as NULL
    lua_pushlightuserdata(L, stdscr);
    lua_setfield(L, -2, "stdscr");

    lua_pushstring(L, VERSION);
    lua_setglobal(L, "_LNCURSES_VERSION");

    // Create a reference to the module table in the registry
    lua_pushvalue(L, -1);
    lua_setfield(L, LUA_REGISTRYINDEX, "lncurses");
    return 1;
}

然后當您initscr ,更新該字段。

static int lncurses_initscr(lua_State* L) {
    initscr();

    // Update "stdscr" in the module table
    lua_getfield(L, LUA_REGISTRYINDEX, "lncurses");
    lua_pushlightuserdata(L, stdscr);
    lua_setfield(L, -2, "stdscr");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM