如何将C++函数公开给lua脚本?

For*_*vin 7 c++ lua function

我刚刚成功创建了一个lua项目.(到目前为止,运行lua脚本的简单代码.)
但是,我现在如何为lua脚本创建c ++函数和c ++变量?

举个例子:

int Add(int x, int y) {
    return x + y;
}
Run Code Online (Sandbox Code Playgroud)

float myFloatValue = 6.0
Run Code Online (Sandbox Code Playgroud)

我对c ++很新,所以我真的希望它不会太复杂.这是我到目前为止得到的代码顺便说一下:

#include "stdafx.h"
extern "C" {
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
}

using namespace System;

int main(array<System::String ^> ^args)
{
    lua_State* luaInt;
    luaInt = lua_open();
    luaL_openlibs (luaInt);
    luaL_dofile (luaInt, "abc.lua");
    lua_close(luaInt);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mah*_*nGM 11

我将与John Zwinck的答案一致,因为经验证明,使用Lua本身就是一个痛苦的屁股.但是,如果你想知道答案,请检查其余部分.

要注册C/C++函数,首先需要让函数看起来像Lua提供的标准C函数模式:

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
}
Run Code Online (Sandbox Code Playgroud)

需要在Lua中注册的每个函数都应遵循此模式.返回类型int,单个参数lua_State* L.并返回值的计数.

然后,您需要在Lua的寄存器表中注册它,以便将它暴露给脚本的上下文:

lua_register(L, "MyFunc", MyFunc);
Run Code Online (Sandbox Code Playgroud)

要注册简单变量,您可以这样写:

lua_pushinteger(L, 10);
lua_setglobal(L, "MyVar");
Run Code Online (Sandbox Code Playgroud)

之后,您可以从Lua脚本调用您的函数.请记住,在运行具有您用于注册它们的特定Lua状态的任何脚本之前,您应该注册所有对象.

在Lua:

print(MyFunc(10, MyVar))
Run Code Online (Sandbox Code Playgroud)

结果:

20

  • 这就是为什么`MyFunc`需要`extern'C"`.`lua_CFunction`是一个指向C链接函数的指针,但``MyFunc`具有C++链接.标准说这些是两种不同的类型,因此它不应该编译(尽管大多数主流编译器错误地接受它). (3认同)