加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Lua C API中克隆Lua表

发布时间:2020-12-14 21:48:08 所属栏目:大数据 来源:网络整理
导读:有很多关于如何在Lua中克隆Lua表的示例,但是我无法找到如何使用本机Lua C API执行此操作的任何示例.我试图用手做两次,但结果却是一个真正的(虽然有效)混乱. 有没有人有关于如何在C API中优雅地执行Lua表的浅表副本的任何提示或链接? 解决方法 您需要做的是
有很多关于如何在Lua中克隆Lua表的示例,但是我无法找到如何使用本机Lua C API执行此操作的任何示例.我试图用手做两次,但结果却是一个真正的(虽然有效)混乱.

有没有人有关于如何在C API中优雅地执行Lua表的浅表副本的任何提示或链接?

解决方法

您需要做的是定义Lua函数,然后将其分解为关联的API调用.

shallow_copy = function(tab)
    local retval = {}
    for k,v in pairs(tab) do
        retval[k] = v
    end
    return retval
end

所以我们需要获取堆栈上的表索引和lua_State.

void shallow_copy(lua_State* L,int index) {

/*Create a new table on the stack.*/

        lua_newtable(L);

/*Now we need to iterate through the table. 
Going to steal the Lua API's example of this.*/

        lua_pushnil(L);
        while(lua_next(L,index) != 0) {
/*Need to duplicate the key,as we need to set it
(one pop) and keep it for lua_next (the next pop). Stack looks like table,k,v.*/


            lua_pushvalue(L,-2);
/*Now the stack looks like table,v,k. 
But now the key is on top. Settable expects the value to be on top. So we 
need to do a swaparooney.*/

            lua_insert(L,-2);

    /*Now we just set them. Stack looks like table,so the table is at -4*/



    lua_settable(L,-4);

/*Now the key and value were set in the table,and we popped off,so we have
table,k on the stack- which is just what lua_next wants,as it wants to find
the next key on top. So we're good.*/

        }
    }

现在我们复制的表位于堆栈的顶部.

基督,Lua API糟透了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读