Good day
开发者_Python百科I have a specific task to give an access of c++ std::map to lua scripts. Desired script syntax is glob["tag"] = "value" or glob("tag") = "value"
In research, have tried luabind binding
std::string & glob(const std::string &tag)
{
static std::string value;
return value;
}
...
luabind::module(&state)
[
def("glob", &glob, luabind::return_reference_to(result))
]
but after run of script listed below
glob("tag") = "asdasd"
print(glob("tag"))
got error [string "glob("tag") = "asdasd"..."]:1: unexpected symbol near '='
So, i'm waiting for your suggestions and opinions.
Thanks
Update 2lhf: Global variables data stored and serialized via c++ part and has to be accessed from lua. luaState is created per script execution, and doesn't exist between executions. One of solution is create and fill global variables table before script execution and sync it with map after execution, but, i think it is slow enough. So, access via c-function with mentioned syntax will be appreciated.
glob("tag") = "asdasd"
can never work, because it's not valid Lua syntax. glob["tag"] = "value"
can work. You need to set glob
as a userdata with index and newindex metamethods. I don't know anything about luabind, so I cannot help you there. But doing it using the standard Lua API is not hard. I just wonder why you need to export C++ map to Lua, when Lua has excellent associative arrays already.
Yep, metatable rules.
Just had to insert some c code get from samples
lua_createtable(&state, 0, 0);
lua_pushcfunction(&state, &getValue);
lua_setfield(&state, -2, "__index");
lua_pushcfunction(&state, &setValue);
lua_setfield(&state, -2, "__newindex");
lua_setmetatable(&state, -2);
lua_setglobal(&state, "global");
And everything works just fine, thanks
But here is another question: why i should use index == -2 for lua_setfield and lua_setmetatable?
精彩评论