gpt4 book ai didi

c - 将 C 变量链接到 Lua

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

我正在寻找将 C 变量(整数、 double 、普通 C 字符串或类似变量)绑定(bind)到 Lua 的解决方案。 Lua 应该能够修改这个变量(在 C 上下文中)。我根本不是在寻找调用 C 函数的解决方案(从 Lua 获取对该变量的引用)。我也不想为此使用任何外部库(Lua API 就可以)。我已经看到 LuaBridge 解决了这个问题(现有项目使用这个:https://github.com/Malaxiz/Third/blob/network/Fifth/CGame.cpp#L240),但正如我所说,没有外部库,绝对不是 C++。

使用示例:

C代码

typedef struct Instance {
int test; /* The variable I want to link to Lua (and be able to modify it)*/
} Instance;

int main() {
lua_State* L = lua_open();
Instance instance;
instance.test = 5;
/* ... */
}

在 Lua 中:

instance.test = instance.test + 5
print(instance.test) -- Should be 10

回到C:

int main() {
...
printf("%i\n", instance.test); /* Should be 10 here too */
}

有解决办法吗?

最佳答案

I'm not looking for a solution to call a C function at all.

你必须这样做。总是会调用 C 函数。即使它在 Lua 端可能不明确,它也会在那里。
通常,您将在 Lua 中的 instance 对象上设置元表。它将捕获对该对象的读取和写入,并通过调用 C 函数将这些操作重定向到 C 端。

关于c - 将 C 变量链接到 Lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42735621/

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