Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute lua string as lua code

Tags:

require

lua

I want to share lua modules with coworkers. In order to get the latest version of shared modules I want to store and fetch them with a web server.

My questions is:

Is it possible to load lua code directly from http request or string?

I want to achieve something like that :

module = [[
    local sharedModule = {}
    function sharedModule.greet(name) print("hello " .. name) end  
    return sharedModule
]]
greeter = require (module)
greeter.greet("john")

Maybe this is not the right thing to do. Is there a better approach than this one?

like image 934
Lionel Briand Avatar asked Jun 06 '17 09:06

Lionel Briand


People also ask

How do you use strings in Lua?

You can initialize strings in Lua in three ways: Use single quotes. Use double quotes. Enclose text between [[ and ]]

How do I run Lua?

To run a Lua scriptOpen the Lua Script Library through Prepare > Run Lua Script. Use the appearing dialog to load, save, and execute Lua scripts as well as to create new ones. Select the script to be run. Click Execute Script.

What is Loadstring Lua?

The loadstring function is similar to loadfile , except that it reads its chunk from a string, not from a file. For instance, after the code f = loadstring("i = i + 1") f will be a function that, when invoked, executes i = i + 1 : i = 0 f(); print(i) --> 1 f(); print(i) --> 2.


1 Answers

There's a whole section in Programming in Lua devoted to that. Your needs will be directly fulfilled with loadstring.

I would carefully verify the code you're actually executing, though. At the very least, version it (running a wrong version would most probably end up in all sorts of problems, if the code being run depends on the environment being in a certain state). Optimally checksum and sign the code, and verify the signature before doing anything. If your environment isn't protected, this is essentially a huge backdoor opening.

You could also use rings library to isolate the code you're running within the Lua environment itself. It might not be airtight security-wise, but should at least prevent the received code from crashing your application if/when it goes awry.

like image 83
Bartek Banachewicz Avatar answered Oct 13 '22 01:10

Bartek Banachewicz