How to load a Lua module as a string instead of a file?

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

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

In other words, I save the Lua source, which will be stored in the .lua file in String. Then I want to load the contents of this line into Lua as an available module that can be called.

I see that there is a loadstring() function, but not sure how it will be called for LuaJava or C.

I do not want Lua to look for the file system for this file, I will find the file and convert it to a string. After I have the line, I need to know how to load a line copy of the contents of the file in Lua as a module that I can call.

I also want to know if, after calling loadstring(s) , if the module remains available for subsequent function calls without reloading loadstring() again.

+4
source share
2 answers

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

If you do not want to load the β€œmodule” from the source several times, you need to give it a name and save some flag in the table. You can even provide β€œunloading” so that you can load the module again from the source. It can be redefined 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 
+3
source

I'm not sure I understand this 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 
+1
source

Source: https://habr.com/ru/post/1387502/


All Articles