How Do I Load Lua Module as a String Instead of a File?

早过忘川 提交于 2019-12-01 18:52:30

问题


I am using LuaJava and C Code for Lua. What I am trying to do is read Lua source stored as a resource String in an Android application so that the Lua source read in can be executed. I need to know how to do this using LuaJava or C language.

I want to know how I can create a Lua module in Lua by using a String.

In other words, I am storing Lua source that would be stored in a .lua file in a String instead. I then want to load the contents of this string into Lua as an available module that can be called.

I see there is a loadstring() function but not sure how this would be invoked for LuaJava or C.

I don't want Lua to search the file system for this file, I will find the file and convert it to a string. After I have the string, I need to know how to load the string copy of the file contents into Lua as a module that I can then call.

I also want to know if after calling loadstring(s) if the module will remain available for subsequent function calls without having to reload do the loadstring() again.


回答1:


If you need to load/compile a string from LuaJava, you can use the function LuaState.LloadString(String source).

If you do not want to load a "module" from source multiple times, you have to assign it a name and save some flag in a table. You can even provide "unloading" so that you could load a module from source again. It could be reimplemented in Lua as follows:

do
  local loadedModules = {} -- local so it won't leak to _G
  function loadModule(name, source)
    if loadedModules[name] then return loadedModules[name] end
    loadedModules[name] = assert(loadstring(source))() or true
  end
  function unloadModule(name)
    loadedModules[name] = nil
  end
end



回答2:


I'm not sure I understand the question but here goes:

local f = io.open(filename)
local s = f:read '*a' -- read the entire contents of the file
f:close()
assert(loadstring(s))() -- parse and run string `s` as Lua code


来源:https://stackoverflow.com/questions/8599597/how-do-i-load-lua-module-as-a-string-instead-of-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!