gpt4 book ai didi

来自 api 的 Lua : How to check if one of the values associated with the specified key of a table is nil,

转载 作者:行者123 更新时间:2023-12-04 03:16:29 25 4
gpt4 key购买 nike

在lua中,这样做是合法的:

table={}
bar
if(table[key]==nil) then
foo

但是,使用 C API,我无法找到检查指定位置是否有 nil 值的方法。

lua_getglobal(L,"table");
lua_gettable(L,key);

如果 table[key] 中存储了一个 nil 值,lua_gettable 会给我“调用 Lua API 时出现不 protected 错误(尝试索引一个 nil 值)”消息。

在实际按下键之前,有什么方法可以检查是否确实有与该键关联的东西?

最佳答案

你错误地调用了 lua_gettable。应该是:

lua_getglobal(L, "tableVar");
lua_pushstring(L, key); //assuming key is a string
lua_gettable(L, -2);

lua_gettable 的第二个参数是表的堆栈索引,而不是键。

如果键是一个字符串,你可以调用lua_getfield代替:

lua_getglobal(L, "tableVar");
lua_getfield(L, -1, key);

关于来自 api 的 Lua : How to check if one of the values associated with the specified key of a table is nil,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705666/

25 4 0