我正在寻找将 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 端。
我是一名优秀的程序员,十分优秀!