【发布时间】:2014-09-25 18:58:57
【问题描述】:
在 C++ 上编程时,您可以执行以下操作:
void byReference(int &y)
{
y = 5;
}
int main()
{
int x = 2; // x = 2
byReference(x); // x = 5
}
如何使用 luabind 做同样的事情?
Luabind 文档says:
如果你想传递一个参数作为引用,你必须把它包装起来 与
Boost.Ref。像这样:
int ret = call_function(L, "fun", boost::ref(val));
但是当我尝试这样做时:
#include <iostream>
#include <conio.h>
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include <luabind\luabind.hpp>
using namespace std;
using namespace luabind;
int main()
{
lua_State *myLuaState = luaL_newstate();
open(myLuaState);
int x = 2;
do
{
luaL_dofile(myLuaState, "script.lua");
cout<<"x before = "<< x <<endl;
call_function<void>(myLuaState, "test", boost::ref(x));
cout<<"x after = "<< x <<endl;
} while(_getch() != 27);
lua_close(myLuaState);
}
script.lua
function test(x)
x = 7
end
我的程序在运行时崩溃并出现以下错误:
0x76B5C42DLuaScripting.exe中的未处理异常:Microsoft C++ 异常:std::runtime_error位于内存位置0x0017F61C。
那么,如何通过引用将值从 C++ 传递给 lua 函数,这样我可以在脚本中更改它,它也会在 C++ 程序中更改?我正在使用 boost 1.55.0、lua 5.1、luabind 0.9.1
编辑:
当我尝试捕捉时
try {
call_function<void>(myLuaState, "test", boost::ref(x));
}catch(const std::exception &TheError) {
cerr << TheError.what() << endl;
它给了我一个"Trying to use unregistered class" 错误。
编辑 2:
经过一番研究,我发现"Trying to use unregistered class" 抛出错误是因为boost::ref(x)。我注册了一个int& 类(只是猜测):
module(myLuaState)
[
class_<int&>("int&")
];
和"Trying to use unregistered class" 错误消失了。但是在test() 中调用print(x) 仍然会导致"lua runtime error",并且程序仍然没有做我想做的事情。
【问题讨论】:
-
<void>在这里做什么:call_function<void>? -
这是一个模板函数:
template<class Ret> Ret call_function(lua_State* L, const char* name, ...)你必须指定返回类型 -
如果你在 test() 中打印 x 并尝试在没有 ref() 的情况下调用它会怎样?
-
@JohnZwinck
function test(x)x = 7print(x)end它给了我“lua运行时错误”。奇怪
标签: c++ boost lua pass-by-reference luabind