从C ++ / C设置全局LUA_PATH变量?
我正在尝试直接从C / C ++设置我的全局LUA_PATH变量,我在我的iPhone应用程序中使用Lua,所以我的路径往往会在应用程序之间发生变化(每个iPhone应用程序在设备中都有一个单独的文件夹)。
我知道我可以通过使用“固定”路径重新编译lua来设置LUA_PATH,但这远非理想。
(我正在尝试这样做,以便能够使用我的.lua
脚本中的.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
ObjC:从另一个答案来看,这对我有用。 需要附加“/?.lua”。
int setLuaPath(NSString * path) { lua_getglobal(L,“package”); lua_getfield(L,-1,“path”); //从堆栈顶部的表中获取字段“path”(-1) NSString * cur_path = [NSString stringWithUTF8String:lua_tostring(L,-1)]; //从堆栈顶部抓取路径字符串 cur_path = [cur_path stringByAppendingString:@“;”]; //在这里做你的道路魔术 cur_path = [cur_path stringByAppendingString:path]; cur_path = [cur_path stringByAppendingString:@“/?。lua”]; lua_pop(L,1); //摆脱我们刚推到第5行的堆栈上的字符串 lua_pushstring(L,[cur_path UTF8String]); //推新的 lua_setfield(L,-2,“path”); //将表中的字段“path”设置为-2,其值为堆栈顶部 lua_pop(L,1); //从堆栈顶部删除包表 返回0; // 全部完成! } ...将此代码添加到某处,例如,在lua_open()附近 //将Lua的Package.path设置为可以找到我们的Lua文件的位置 NSString * luaPath = [[NSBundle mainBundle] pathForResource:@“我的任何一个lua文件的名称”ofType:@“lua”]; setLuaPath([luaPath stringByDeletingLastPathComponent]); ...
您也可以在调用require
之前更改Lua中的package.path
。
您可以通过执行一对lual_dostring函数,非常轻松地在c ++中设置LUA_PATH和LUA_CPATH。
luaL_dostring(L, "package.path = package.path .. ';?.lua'"); luaL_dostring(L, "package.cpath = package.cpath .. ';?.dll'");
在您拥有lua_State(此处为L)之后,在您的lual_loadfile()和lau_pcall()函数调用将添加到当前设置的路径和cpath之前调用这两行。 在这种情况下,我添加了一条指令,以查看执行的本地。
我花了几个小时才找到这个解决方案..我希望它有所帮助。
#include
…
setenv ( "LUA_PATH", (char *)my_path, 1 );
…或类似的东西…
我想这是不可能的,因为正如你所提到的,出于安全原因,每个iPhone应用程序都存在于自己的沙盒中。
我认为使用setenv
只会为当前进程和子进程设置环境变量。
顺便说一句:如果计划将您的应用程序提交到AppStore,(据我所知)脚本语言/口译员会受到您签署的合同的影响。
我对iPhone开发不太熟悉,但是你可以在执行应用程序之前设置LUA_PATH env变量吗?
例如,在Linux中,我可以编写一个执行二进制文件的脚本,如下所示:
export LUA_PATH="foo" /path/to/executable
Windows具有与批处理文件类似的function。
如果你真的需要在代码中更改它,我不知道如何使用luaL_loadbuffer和lua_pcall来执行“package.path = blah”命令。