尝试通过 Android 上的要求访问资产中的 Lua 脚本

Trying to access Lua scripts in assets via require on Android

我最近尝试将我一直在研究的引擎移植到 Android,但在尝试使用 "require" 或 "dofile" 时遇到了一些问题 运行在 lua 脚本中。

(注意:这是用 C++11 编写的,使用 ndk-build 和 ant 在 windows 7 上编译)

编译 Lua(5.3 版)非常简单,我使用了以下文章来访问内部资产目录: 50ply blog post on loading compressed android assets

我在替换的 fopen 函数中添加了一个输出来帮助调试这个问题,当我 运行:

luaL_dofile(LuaS, "scripts/test.lua");

我得到:

>> scripts/test.lua , read

这对我来说是完美的,运行s 是 assets/scripts 文件夹中的文件,但是当我尝试 运行 lua 脚本中的以下行时:

local derp = require("scripts.noop")

我得到:

>> /usr/local/lib/lua/5.3/scripts/noop.so , read

看了Lua源码,这个路径好像是"luaconf.h"中定义的"LUA_CDIR",这也解释了为什么要找*.so文件而不是*.lua... 所以我不确定它为什么要寻找 LUA_CPATH 而不是 LUA_PATH 或如何解决这个问题。

如果有人能给我指出正确的方向,那就太好了,如果我可以通过覆盖 Lua 源之外的搜索 path/settings 来做到这一点,那就更好了。

抱歉,如果这个问题写得不好,如果需要任何进一步的信息,我会提供。我现在有点赶时间。

感谢阅读。

Require 检查 LUA_PATHLUA_CPATH,并在 package.pathpackage.cpath 中找到许多不同的组合。环境变量 LUA_PATH 和 LUA_CPATH 可以发现实际上已经合并到包中了,随着准备工作的进行。

Psuedo-c/c++-示例:

lua_getglobal(L, "package");
lua_getfield(L, -1, "path");
lua_getfield(L, -2, "cpath");
const char* cpath = lua_tostring(L, -1);
const char* path = lua_tostring(L, -2);
lua_pop(L, 3); // field 2, field 1, package table
printf("cpath: `%s`\n", cpath);
printf("path: `%s`\n", path);

这几乎等同于减去打印调用:

>print(package.cpath)
.\?.dll;C:\Program Files\LuaConsole\bin\?.dll;C:\Program Files\LuaConsole\bin\loadall.dll
>print(package.path)
.\?.lua;C:\Program Files\LuaConsole\bin\lua\?.lua;C:\Program Files\LuaConsole\bin\lua\?\init.lua;

这是一个需要工作的例子:

>require("abc")
 (Runtime) | Stack Top: 0 | [string "require("abc")"]:1: module 'abc' not found:

        no field package.preload['abc']
        no file '.\abc.lua'
        no file 'C:\Program Files\LuaConsole\bin\lua\abc.lua'
        no file 'C:\Program Files\LuaConsole\bin\lua\abc\init.lua'
        no file '.\abc.dll'
        no file 'C:\Program Files\LuaConsole\bin\abc.dll'
        no file 'C:\Program Files\LuaConsole\bin\loadall.dll'
 --
stack traceback:
        [C]: in function 'require'
        [string "require("abc")"]:1: in main chunk
        [C]: at 0x00401c80

您的问题的解决方案是将您的资产目录放入 package.cpathpackage.path 内的目录中。正如@GabeSechan 在评论中建议的那样,"You'll probably have an easier time of things if you copy the files from assets to the actual filesystem. Assets is not a directory on the device, so anything looking for a file won't find it." 因此,如果您能够找到这个位置,那就去吧!