gpt4 book ai didi

c - 如何从 C 中的 lua 访问多维表?

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:54 24 4
gpt4 key购买 nike

您好,我真的被这个看似简单的任务难住了。我可以访问传递给 C 函数的表的属性,但无法访问我在其中创建的任何子表的成员。

基本上,我只想从属性表中提取字符串,这样我就可以根据用户的期望创建一个“轮子”。

这是我目前所拥有的(尝试了这么多我的脑子都炸了)

Lua 端:

--Function
createSomething( "wheel", { canInflate = true, properties = { "large", "full" } } )

C 端:

//I can retrieve any value easily within that table, but cannot seem to extract the table
//Within it named "properties", i can access the table, but cannot extract the strings inside

if( lua_istable(L, 2) ) {
lua_getfield(L, 2, "canInflate"); // Let's extract the value for the key 'someKey'. Pushes the value on the top of the stack
static int canInflate = lua_toboolean(L, -1); // get the value of bool now at the top of stack (index: -1)

//printf("can inflate is %d\n", canInflate);
//lua_pop(L, 1); // pop the value now that we are done with it
}


//try to get the properties table
if ( lua_istable(L, 2) ) {
lua_getfield(L, 2, "properties");

const char *str = lua_tostring(L, -1);

printf( "properties 1 = %s\n", str); // NULL

lua_pop(L, 2);
}

如有任何帮助,我们将不胜感激

最佳答案

您遇到的问题是您如何在 Lua 中指定表:以下 3 个语句具有完全相同的结果:

t = { 'full','large'}
t = { [1] = 'full', [2] = 'large'}
t={};t[1]='full';t[2]='large'

您想要的是将字符串用作键而不是值(如您的代码和上述示例中所做的那样):

t={full=true,large=true}
-- or
t={}; t.full=true; t.large=true

如果您使用字符串作为键,您的 C 代码应该可以工作。

关于c - 如何从 C 中的 lua 访问多维表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471883/

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