从 C++/C 设置全局 LUA_PATH 变量?

Setting the global LUA_PATH variable from C++/C?(从 C++/C 设置全局 LUA_PATH 变量?)

本文介绍了从 C++/C 设置全局 LUA_PATH 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图直接从 C/C++ 设置我的全局 LUA_PATH 变量,我在我的 iPhone 应用程序中使用 Lua,所以我的路径往往会在应用程序之间发生变化(每个 iPhone 应用程序在设备中都有一个单独的文件夹).

I'm trying to set my global LUA_PATH variable directly from C/C++, I'm using Lua from my iPhone applications, so my path tends does change between applications ( each iPhone app has a separate folder in the device ).

我知道我可以通过使用固定"路径重新编译 lua 来设置 LUA_PATH,但这远非理想.

I know I could set the LUA_PATH by recompiling lua with a "fixed" path, but that's quite far from ideal.

(我试图这样做是为了能够从我的 .lua 脚本中使用 require.

( I'm trying to do this in order to be able to use require, from my .lua scripts.

有人可以帮我吗?

推荐答案

在 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

I haven't tested or compiled it. I used: http://lua.org/pil and http://lua.org/manual/5.1

这篇关于从 C++/C 设置全局 LUA_PATH 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 C++/C 设置全局 LUA_PATH 变量?

基础教程推荐