gpt4 book ai didi

c++ - 加载Lua文件并使用变量而不执行函数

转载 作者:行者123 更新时间:2023-11-30 02:27:30 25 4
gpt4 key购买 nike

我正在尝试从 Lua 将表格加载到 C++ 中。这是文件的样子:

function alma(arg)
print(arg)
end

sometable = {
num = 5,
text = "this is a string",

nested = {
{"a", alma("argument")},
{"table", alma("arg")},
{"element", alma("asd")}
}
}

如果我调用 luaL_loadfile,我只会得到 block 。如果我调用 lua_dofile 我会得到元素,但是 alma 函数会针对每个元素运行。在 this SO线程,有人说要将这些东西包装到函数中并调用它来获取数据。当我包装/调用该函数时,3 个 alma 函数在我调用 getter 时运行。如何在不执行 alma 函数的情况下获取 sometable 及其元素?

最佳答案

and I'd like to have onClick events for gui elements, which would be some functions, hence the {"some string", function} table elements

好的,您需要稍后调用的函数。只需保存该函数的值,即简单地写下它的名称:

nested = {
{"a", func_argument},
{"table", func_arg},
{"element", func_asd}
}

但是你想调用相同的函数,传递参数。并且您希望将该信息保存为一个函数。因此,要么直接在表中定义一个函数,要么调用一些将返回另一个函数的函数,将其参数存储在闭包中:

-- function to be called
function alma(arg)
print(arg)
end

-- define functions in table
nested1 = {
{"a", function() alma "argument" end},
{"table", function() alma "arg" end},
{"element", function() alma "asd" end}
}

-- or create function within another function
function alma_cb(name)
return function() alma(name) end
end

nested2 = {
{"a", alma_cb "argument"},
{"table", alma_cb "arg"},
{"element", alma_cb "asd"}
}

关于c++ - 加载Lua文件并使用变量而不执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com