Leafli Leafli - 3 months ago 19
Python Question

Implementing External Source Code Block in Lua

I'm looking to write a Lua script and have it also execute something from Python source code as well, as if it went like so:

#!/bin/lua

-- begin lua part
print "Hello"

--begin python part

Somehow_Executes_Python {
print "Hello" #In python, of course
}

-- End Script


Getting the idea?
I'm not sure if it's even possible, but if I can somehow implement foreign source code in controlled blocks, that would be great. I've seen other things about calling them from a different file/ link/ source, but I'm looking to have it work directly from inside of the lua source code, not from a different file entirely.

Answer

The simplest approach would be something along these lines:

#!/usr/bin/env lua

local python = function(code)
  local file = assert(io.popen('python', 'w'))
  file:write(code)
  file:close()
end

-- begin lua part
print "Hello from Lua"

--begin python part

python [=[
print "Hello from Python"
]=]

-- End Script

Line-by-line explanation (without code highlighting, it seems that it is broken for Lua on the SO):

#!/usr/bin/env lua
-- The above is a more sure-fire way to run Lua on linux from a shebang

-- This function runs python code as follows
local python = function(code)
  -- It opens a write pipe to the python executable
  local file = assert(io.popen('python', 'w'))
  -- pipes the code there
  file:write(code)
  -- and closes the file
  file:close()
  -- This is an equivalent of running
  -- $ python <code.py
  -- in the shell.
end

-- Begin Lua part
-- I added "from Lua" to better see in the output what works or not.
print "Hello from Lua"

-- Begin Python part
-- We're calling our python code running function, 
-- passing Lua long string to it. This is equivalent of
-- python('print "Hello from Python"')
python [=[
print "Hello from Python"
]=]

-- End Script

I imagine you would like to have at least some interoperability between Lua and Python code. It is a bit more difficult to implement and the way you should do it highly depends on the details of the problem you're actually solving.

The cleanest way would probably to create a socket pair of one kind or another and to make Lua and Python code to talk over it.

Solutions where you may read a variable or call a function from one VM (say Lua) in another (say Python) and vice-versa usually lead to a mess for a multitude of reasons (I tried a lot of them and implemented several myself).

Comments