问题描述
对于我正在研究的项目,我需要向Lua公开另一个库中的一些C ++类.不幸的是,该库中最重要的类之一具有许多联合和枚举( SFML 中的sf :: Event类),以及我发现没有任何关于将C ++联合暴露给Lua的内容.我不介意它是通过Lua/C API,库或绑定生成器公开的,只要它可以工作.但是,我不想使用绑定生成器,因为我希望能够在C ++中创建一个对象,然后将该对象的实例暴露给Lua(除非绑定生成器可以做到)
For a project I'm working on, I need to expose some C++ classes in another library to Lua. Unfortunately, one of the most important classes in this library has lots of Unions and Enums (the sf::Event class from SFML), and from a quick Google search I've discovered there is nothing on exposing C++ Unions to Lua. I don't mind if it's being exposed with the Lua/C API, with a library or with a binding generator, as long as it works. But, I'd prefer not to use a binding generator, because I want to be able to create an object in C++, then expose that instance of the object to Lua (unless that's possible with a binding generator)
推荐答案
要注册C/C ++函数,您首先需要使函数看起来像Lua提供的标准C函数模式:
For registering C/C++ functions you need to first make your function look like a standard C function pattern which Lua provides:
extern "C" int MyFunc(lua_State* L)
{
int a = lua_tointeger(L, 1); // First argument
int b = lua_tointeger(L, 2); // Second argument
int result = a + b;
lua_pushinteger(L, result);
return 1; // Count of returned values
}
需要在Lua中注册的每个功能都应遵循此模式.返回类型int
和lua_State* L
的单个参数.并计算返回值.然后,您需要在Lua的register表中注册它,以便可以将其公开到脚本的上下文中:
Every function that needs to be registered in Lua should follow this pattern. Return type of int
, single parameter of lua_State* L
. And count of returned values.Then, you need to register it in Lua's register table so you can expose it to your script's context:
lua_register(L, "MyFunc", MyFunc);
要注册简单变量,您可以这样编写:
For registering simple variables you can write this:
lua_pushinteger(L, 10);
lua_setglobal(L, "MyVar");
之后,您可以从Lua脚本中调用函数.请记住,在运行具有用于注册对象的特定Lua状态的脚本之前,应先注册所有对象.
After that, you're able to call your function from a Lua script. Keep in mind that you should register all of your objects before running any script with that specific Lua state that you've used to register them.
在Lua:
print(MyFunc(10, MyVar))
结果:
20
我想这可以帮助您!
这篇关于如何向Lua公开C ++联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!