类似 Lua switch 的语句,带有 case Fallthroughs,可通过 C api 访问

问题描述 投票:0回答:1

尝试构建一个根据整数结果查找效果的表。

有些结果在一个范围内,例如 1 到 5,但最终会出现一堆结果。

http://lua-users.org/wiki/SwitchStatement

展示了其中的一些内容,但“方便地”认为没有必要提及任何有关 C api 的内容。

那么,我如何从 C api 访问具有数字索引的表/数组的字段? 此时,我很高兴有一个冗余解决方案,该解决方案复制条目以覆盖范围,对我来说,问题在于使用数字索引获取字段的 C api 部分。

Tables = {}


Tables.Effects = {
[1] = "effect 1"
.... 
}

如果我必须准确地解释我尝试过的内容,那么我就必须回到过去并使用

写下无数盲目摸索的排列

lua_getglobal

lua_getfield

lua_pushnumber

之类的

也许这很简单,只需用勺子喂食即可? lua状态被初始化。该文件没有错误,并通过 luaL_dofile 等加载。

目前,为了完成工作,我将使用数字到字符串的方法,尽管这可能很糟糕,因为这样我就可以使用

lua_getfield
。实际上,我们应该使用辅助代理函数,然后通过 Lua 本身对表进行索引。

编辑: 在尝试了评论中使用 lua_geti 的建议后 我失败了以下几点:

void accessTables(lua_State* L, int value)
{
    lua_getglobal(L, "Tables.Effects"); 
    lua_geti(L, -1,value); 
    if (lua_pcall(L, 0, 0, 0) != 0) { // it actually is an array of functions, so calling them should be fine
        std::cout <<  "error running function `f':" << lua_tostring(L,-1)  << '\n';
    }

}

但是即使传递的值是有效的索引,我也会收到以下错误:

| PANIC: unprotected error in call to Lua API (attempt to index a nil value)

arrays c lua lua-api
1个回答
0
投票

正如 ESkri 所说,当我应该手动完成这些步骤时,我尝试直接使用“点”表示法,从而错误地处理了数组。

因此:

void accessTables(lua_State* L, int value)
{
    lua_getglobal(L, "Tables"); 
    lua_getfield(L,-1, "Effects"); // the manual step
    lua_geti(L, -1,value); //now it pushes the function onto the stack
    if (lua_pcall(L, 0, 0, 0) != 0) { //call it
        std::cout <<  "error running function `f':" << lua_tostring(L,-1)  << '\n';
    }
    lua_pop(L,2); //Only through experimentation I realized that the first getglobal stack entries with the table references had to be popped, but the function stack entry did not
//without the poppage, the stack grew by two entries each time I called it.
}

成功了

© www.soinside.com 2019 - 2024. All rights reserved.