更新时间:2022-02-04 02:44:39
要注册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
我想这可以帮助您!