When programming on C++, you can do the following:
void byReference(int &y)
{
y = 5;
}
int main()
{
int x = 2; // x = 2
byReference(x); // x = 5
}
How to do the same using luabind?
Luabind docs says:
If you want to pass a parameter as a reference, you have to wrap it with the
Boost.Ref
.Like this:
int ret = call_function(L, "fun", boost::ref(val));
But when I'm trying to do this:
#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
My program crashes at runtime with the following error:
Unhandled exception at at
0x76B5C42D
inLuaScripting.exe
: Microsoft C++ exception:std::runtime_error
at memory location0x0017F61C
.
So, how to pass value from C++ to lua function by reference, so I can change it inside the script and it will be changed in c++ program too? I'm using boost 1.55.0, lua 5.1, luabind 0.9.1
EDIT :
When I try-catched
try {
call_function<void>(myLuaState, "test", boost::ref(x));
}catch(const std::exception &TheError) {
cerr << TheError.what() << endl;
it gave me a "Trying to use unregistered class"
error.
EDIT 2 :
After a little research, I found that "Trying to use unregistered class"
error throwing because of boost::ref(x)
. I registered a int&
class(just a guess):
module(myLuaState)
[
class_<int&>("int&")
];
and "Trying to use unregistered class"
error disappeared. But calling print(x)
in test()
still causes "lua runtime error"
, and program still not doing what I want from it to do.