我试图直接从C/C++设置我的全局LUA_PATH变量,我从我的iPhone应用程序中使用Lua,所以我的路径倾向于在应用程序之间改变(每个iPhone应用程序在设备中都有一个单独的文件夹)。
我知道我可以通过使用“固定”路径重新编译lua来设置LUA_PATH,但这与理想情况相去甚远。
(我正在尝试这样做,以便能够使用require
脚本中的.lua
。
有人可以帮我吗?
最佳答案
在C++中:
int setLuaPath( lua_State* L, const char* path )
{
lua_getglobal( L, "package" );
lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1)
std::string cur_path = lua_tostring( L, -1 ); // grab path string from top of stack
cur_path.append( ";" ); // do your path magic here
cur_path.append( path );
lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5
lua_pushstring( L, cur_path.c_str() ); // push the new one
lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack
lua_pop( L, 1 ); // get rid of package table from top of stack
return 0; // all done!
}
我还没有测试或编译它。我曾经使用过:http://lua.org/pil和http://lua.org/manual/5.1