I wonder if it's possible to access the variables of the class that runs the Lua script from the bound C++ class that is being used in Lua script.
From the example below, I wonder if it's possible to access name
variable in myLua
class from the bound Test
class somehow.
Here are my codes.
main.cpp :
extern "C"
{
int luaopen_my(lua_State* L);
}
class myLua {
public:
struct myData
{
std::string name;
lua_State *L;
};
myLua(std::string name)
{
data = make_shared<myData>();
data->name = name;
data->L = luaL_newstate();
lua_State *L = data->L;
luaL_openlibs(L);
luaopen_my(L);
lua_settop(L, 0);
const char *script =
"function setup() \
test = my.Test() \
test:callHello() \
end \
function hello(name) \
print('hello is called by : ' .. name) \
end";
//------------Added----------------
lua_pushlightuserdata(L, data.get());
myLua::myData *b = static_cast<myLua::myData *>(lua_touserdata(L, 1));
cout << "RESULT1 : " << b->name << endl;
//---------------------------------
const int ret = luaL_loadstring(L, script);
if (ret != 0 || lua_pcall(L, 0, LUA_MULTRET, 0) != 0)
{
std::cout << "failed to run lua script" << std::endl;
return;
}
lua_getglobal(L, "setup");
if (lua_pcall(L, 0, 0, 0))
{
std::cout << "failed to call setup function" << std::endl;
return;
}
}
shared_ptr<myData> data;
};
void main()
{
myLua lua1("Apple");
myLua lua2("Orange");
}
bindings.h :
class Test
{
public:
void callHello(lua_State *L) {
//------------Added----------------
myLua::myData *b = static_cast<myLua::myData *>(lua_touserdata(L, -1));
cout << "RESULT2 : " << b->name << endl;
//---------------------------------
lua_getglobal(L, "hello");
lua_pushstring(L, "ClassName");
if (lua_pcall(L, 1, 0, 0))
{
std::cout << "failed to call hello function" << std::endl;
return;
}
};
};
bindings.i : (Used to bind bindings.h
using SWIG)
%module my
%{
#include "bindings.h"
%}
%include <stl.i>
%include <std_string.i>
%include <std_vector.i>
%include <std_map.i>
%include <typemaps.i>
%typemap(default) (lua_State *L)
{
$1 = L;
}
typedef std::string string;
%include "bindings.h"
Current result:
hello is called by : ClassName
hello is called by : ClassName
Result I want :
hello is called by : Apple
hello is called by : Orange
Maybe I can register the variable to lua_State*
somehow?
I think it would be great if there's something like
lua_registerdata(L, &name);
And then later get it using something like
string name = lua_getregistereddata(L);
Result with the added code:
RESULT1 : Apple
RESULT2 : \360n\240\300`\255\276\255\336\336\300ݺ\220\300`DD\255\276\255\336\336\300ݺ\300\217\300`\340_\300`D\376
hello is called by : ClassName
RESULT1 : Orange
RESULT2 : \360n\300`\255\276\255\336\336\300ݺ\200\236\300`DD\255\276\255\336\336\300ݺ@\236\300``w\300`D\376
hello is called by : ClassName