在 Lua 中注册 C++ 函数?

2023-09-27C/C++开发问题
12

本文介绍了在 Lua 中注册 C++ 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试在 Lua 中注册一个 C++ 函数.

I am trying to register a c++ function in Lua.

但收到此错误:

CScript.cpp|39|error: argument of type 'int (CScript::)(lua_State*)' does not match 'int (*)(lua_State*)'|

int CApp::SetDisplayMode(int Width, int Height, int Depth)
{
    this->Screen_Width = Width;
    this->Screen_Height = Height;
    this->Screen_Depth = Depth;

    return 0;
}

int CScript::Lua_SetDisplayMode(lua_State* L)
{
  // We need at least one parameter
  int n = lua_gettop(L);
  if(n < 0)
  {
    lua_pushstring(L, "Not enough parameter.");
    lua_error(L);
  }

  int width = lua_tointeger(L, 1);
  int height = lua_tointeger(L, 2);
  int depth = lua_tointeger(L, 3);

  lua_pushinteger(L, App->SetDisplayMode(width, height, depth));

  return 0;
}

在主要部分:

lua_register(L, "setDisplayMode", Lua_SetDisplayMode);

推荐答案

您不能直接使用基本的 Lua C API 在 Lua 中注册 C++ 非静态成员函数.

You cannot directly register a C++ non-static member function in Lua using just the basic Lua C API.

然而,任何可以轻松将 C++ 代码与 Lua 相关联的各种机制都允许您这样做.toLua++、SWIG、Luabind 等.如果你是认真的在 Lua 中使用 C++ 对象,我建议选择其中之一并使用它,而不是编写自己的版本.我个人使用 Luabind(大部分时间;SWIG 在工具箱中占有一席之地),因为它没有某种形式的代码生成.这一切完全是在 C++ 中完成的,因此没有生成 C++ 源文件的预通过步骤.

However, any of the various mechanisms that exist for easily associating C++ code with Lua will allow you to do so. toLua++, SWIG, Luabind, etc. If you're serious about using C++ objects with Lua, I suggest picking one of those and using it, rather than writing your own version. I personally use Luabind (most of the time; SWIG has its place in the toolbox), as it is the one that doesn't have some form of code generation. It's all done purely in C++, so there's no pre-pass step that generates a C++ source file.

这篇关于在 Lua 中注册 C++ 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6